May 18, 2013

Why Java Calculates Date Time Wrong

I needed to iterate through a date-time range and observed some strange behavior from Java. So I want to iterate hour by hour from 2011-10-05-00 until  2013-02-13-23. The code I was expecting was
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH");
  
Calendar c = new GregorianCalendar(2011, 10, 5, 0, 0);  
Calendar cEnd = new GregorianCalendar(2013, 2, 14, 00, 0);
  
while (c.getTime().before(cEnd.getTime())) {
 System.out.print(format.format(c.getTime()) + "[");
 System.out.println(c.getTimeInMillis() + "](" + cEnd.getTimeInMillis() + ")");
 c.add(Calendar.HOUR, 1);
}

For some strange reason that I haven't figured out yet this will iterate from 2011-10-05-00 until 2013-03-13 23 (one month later than I'd expected!).

Parse the string first!
like here and here, also pay attention to the formatting parameters.
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH");
Calendar c = Calendar.getInstance();
c.setTime(format.parse("2011-10-05 00"));
Calendar cEnd = Calendar.getInstance();
cEnd.setTime(format.parse("2013-02-13 23"));

while (c.getTime().before(cEnd.getTime())) {
 System.out.print("hi " + format.format(c.getTime()) + "]");
 System.out.println(c.getTimeInMillis() + "]["+ cEnd.getTimeInMillis());
 c.add(Calendar.HOUR, 1);
}
Moral of the story: use Joda Time: here.


No comments:

Post a Comment