Friday, July 4, 2014

Java: Comparing date with today's date

Usually in Java, if you want to compare there are three methods (that I know of); using DateFormat; using Calendar; and using milliseconds since epoch. The following is how I do date comparison for each methods (starting from the slowest based on my own tests) with d as the target date:

Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, -5); // 5 days ago.
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date d = cal.getTime();

DateFormat

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date today = sdf.parse(sdf.format(new Date));
boolean isBeforeToday = d.getTime() < today.getTime();
boolean isToday = d.getTime() == today.getTime();
boolean isAfterToday = d.getTime() > today.getTime();

Calendar

This is quite fast, so if you prefer readability, I suggest you choose this.
 
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// I think you can also use Calendar.before() & Calendar.after()...
boolean isBeforeToday = d.getTime() < cal.getTime().getTime();
boolean isToday = d.getTime() == cal.getTime().getTime();
boolean isAfterToday = d.getTime() > cal.getTime().getTime();
 

Milliseconds

 I prefer this method, which I believe the fastest. But it's the least readable...

long now = new Date().getTime();
long delta = d.getTime() - now;
boolean isBeforeToday = delta <= -86400000; // 24*60*60*1000, milliseconds in a day
boolean isToday = delta <= 0 && delta > -86400000;
boolean isAfterToday = delta > 0;

NOTE: Don't use this if the time part of java.util.Date is non-zero. :)