Featured Post

The great debacle of healthcare.gov

This is the first time in history when the president of the United States of America, or probably for any head of state around the world,...

Wednesday, March 5, 2008

Date difference dependens on the underlying JVM

If you write a utility method to get the difference between two dates, don't trust your system that it's gonna give you the same result all the time (Don't confused it with the Java slogan 'write once, run anywhere' !). The result you would get is totally dependent on the JVM, on which you are running your code. Follow the below case:

1. Create a date object from the Calendar:

Calendar cal = GregorianCalendar.getInstance();

cal.set(2008, Calendar.JANUARY, 31);
startDate = cal.getTime();

cal.set(2014, Calendar.MARCH, 31);
endDate = cal.getTime();

2. Get the difference in days:

long time1 = startDate.getTime();
long time2 = endDate.getTime();
long inDays = (time2 - time1) / 1000 * 60 * 60 * 24;

3. The result is 2250 days in -
Java(TM) 2 Runtime Environment, Standard Edition (IBM build 1.4.2_12-b03 20061117 (SR6 + 110979) ) and 2251 in Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_04-b05).

The true platform independent solution for the above issue is to add the hour:min:sec
as 23:59:59 while getting the date from the calendar.

cal.set(2014, Calendar.MARCH, 31, 23, 59, 59);

And through that you can write once and run anywhere until any new issue come up.

Note: Though I'm not yet sure but I found some posting that says this happens only if the date falls in some leap year.

No comments: