Why is this Java Calendar comparison bad?
Posted
by joe7pak
on Stack Overflow
See other posts from Stack Overflow
or by joe7pak
Published on 2010-03-22T13:51:08Z
Indexed on
2010/03/22
14:11 UTC
Read the original article
Hit count: 244
java
Hello folks.
I'm having an inexplicable problem with the Java Calendar class when I'm trying to compare to dates. I'm trying to compare to Calendars and determine if their difference is > than 1 day, and do things bases on that difference or not. But it doesn't work.
If I do this with the two dates:
String currDate = aCurrentUTCCalendar.getTime().toString();
String localDate = aLocalCalendar.getTime().toString();
I get these results:
currDate = "Thu Jan 06 05:58:00 MST 2010"
localDate = "Tue Jan 05 00:02:00 MST 2010"
This is correct.
But if I do this:
long curr = aCurrentUTCCalendar.getTime().getTime();
long local = aLocalCalendar.getTime().getTime();
I get these results: ( in milliseconds since the epoch )
curr = -125566110120000
local = 1262674920000
Since there is only about a 30 hour different between the two, the magnitudes are vastly different, not to mention that annoying negative sign.
This causes problems if I do this:
long day = 60 * 60 * 24 * 1000; // 86400000 millis, one day
if( local - curr > day )
{
// do something
}
What's wrong? Why are the getTime().toString() calls correct, but the getTime().getTime() calls are vastly different?
I'm using jdk 1.6_06 on WinXP. I can't upgrade the JDK for various reasons.
© Stack Overflow or respective owner