Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bug in Java Calendar / Date for 2nd October 2010?

Tags:

java

date

I'm not sure what I'm doing wrong, but I've got a piece of code which calculates the number of days between two dates, and which looks something like the following:

final Calendar first = new GregorianCalendar(2010, Calendar.OCTOBER, 1);
final Calendar last = new GregorianCalendar(2010, Calendar.NOVEMBER, 1);

final long difference = last.getTimeInMillis() - first.getTimeInMillis();
final long days = difference / (1000 * 60 * 60 * 24);

System.out.println("difference: " + difference);
System.out.println("days: " + days);

To summarise, the code block above calculates the number of days between 1st October 2010 and 1 November 2010. I'm expecting to see it return 31 days (seeing as there's 31 days in October)

difference: xxxx
days: 31

but instead it's showing 30 days in October!

difference: 2674800000
days: 30

I've managed to narrow it down to between the the dates 2 October 2010 and 3 October 2010, which seems to only have 82800000 milliseconds, instead of a full 86400000 milliseconds (exactly one hour missing).

Does anyone have any ideas what I'm doing wrong? Or is the 2nd October a special date which has one minute less than a regular day?

like image 872
jklp Avatar asked Dec 17 '10 06:12

jklp


1 Answers

(86400000 - 82800000)/1000 = 3600, which is one hour. You're seeing daylight savings time, combined with the rounding of integer math

You could get around it by doing the calculations with floating point numbers and rounding at the end, or you could check out a library like Joda time which offers much better date math than what's built in.

like image 159
Brad Mace Avatar answered Sep 23 '22 19:09

Brad Mace