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 tocompare. use “public long getTime()” method of each date object to obtain number ofmilliseconds since January 1, 1970, 00:00:00 GMT for each date, andcompare these long values using operators <, >, ==, <>, != as you see fit.
2. Obtain two instances of the java.util.Calendar class through a call toone of the “public static synchronized Calendar getInstance(…)” methods of theCalendar instance. Set the date of each Calendar instance using one of its “public final voidset(…)” 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 adate 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);
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: