Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Oct 6, 1999

Date Comparison in Java

To compare dates in Java you have two choices:
1. Create java.util.Date objects based on the dates that you'd like to compare. use "public long getTime()" method of each date object to obtain number of milliseconds since January 1, 1970, 00:00:00 GMT for each date, and compare these long values using operators <, >, ==, <>, != as you see fit.
2. Obtain two instances of the java.util.Calendar class through a call to one of the "public static synchronized Calendar getInstance(...)" methods of the Calendar instance. Set the date of each Calendar instance using one of its "public final void set(...)" methods.
Then use Calendar methods:
 
"public abstract boolean equals(Object obj)",
"public abstract boolean after(Object when)",
"public abstract boolean before(Object when)"

to do the comparison, The following code uses the latter:

 
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();

int year = 1999;
int month = 11;
int day1 = 10;
int day2 = 11;

cal1.set(year,month,day1);
cal2.set(year,month,day2);

String date1 = ""+year+"//"+month+"//"+day1;
String date2 = ""+year+"//"+month+"//"+day2;

if( cal2.equals(cal1) )
        System.out.println(date1+" is the same as " + date2);
if( cal2.after(cal1) )
        System.out.println(date2 + "is after "+date1);
else
        System.out.println(date2 + "is before "+date1);
To do so, you can use java.text.SimpleDateFormat to format string into a date format:
 
SimpleDateFormat formatter= new SimpleDateFormat("ddMMyyyy HHmm");
String dateStr = null;    
try
{
     dateStr = formatter.parse(dateString);
}
catch (Exception e)
{
     //handle exception
}
Or, use java.util.Calendar class:
 
java.util.Calendar cal1 = java.util.Calendar.getInstance();
java.util.Calendar cal2 = java.util.Calendar.getInstance();

int year = 1999;
int month = 11;
int day1 = 10;
int day2 = 11;

cal1.set(year,month,day1);
cal2.set(year,month,day2);

String date1 = ""+year+"/"+month+"/"+day1;
String date2 = ""+year+"/"+month+"/"+day2;

if( cal2.equals(cal1) )
        System.out.println(date1+" is the same as " + date2);
if( cal2.after(cal1) )
        System.out.println(date2 + " is after "+date1);
if (cal2.before(cal1))
        System.out.println(date2 + " is before "+date1);
Behrouz Fallahi
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date