Why is this Java Calendar comparison poor?

I am having an inexplicable problem with the Java Calendar class when I try to compare with dates. I am trying to compare with Calendars and determine if their difference is> 1 day, and do something based on this difference or not. But that does not work.

If I do this with two dates:

String currDate = aCurrentUTCCalendar.getTime().toString(); String localDate = aLocalCalendar.getTime().toString(); 

I get the following results:

  currDate = "Thu Jan 06 05:58:00 MST 2010" localDate = "Tue Jan 05 00:02:00 MST 2010" 

It is right.

But if I do this:

  long curr = aCurrentUTCCalendar.getTime().getTime(); long local = aLocalCalendar.getTime().getTime(); 

I get the following results: (in milliseconds from the era)

  curr = -125566110120000 local = 1262674920000 

Since there is only about 30 hours between them, the values ​​differ significantly from each other, not to mention the fact that the 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 happened? Why getTime ()? ToString () is correct, but calls getTime (). GetTime () are very different?

I am using jdk 1.6_06 on WinXP. I cannot update the JDK for various reasons.

+4
source share
3 answers

The answer was to use the JodaTime class. Thanks for the introduction, it was easier to get the results that I wanted, instead of using Java files.

I leave this as one of the oddities of those Java.Util.Date and Java.Util.Calendar classes.

Thanks for the help.

0
source

Your current currency is BCE 2010-01-06 ( BC ), which is 4019 (2x2010 - 1) years ago.

Try the following:

 public class StrangeDate { public static void main(String[] args) { Date d = new Date(-125566110120000L); System.out.println(d.toString()); //prints 'Thu Jan 06 13:58:00 CET 2010' in my locale Calendar c = Calendar.getInstance(); c.setTime(d); c.add(Calendar.YEAR, 4019); System.out.println(c.getTime().toString()); //prints 'Wed Jan 06 13:58:00 CET 2010' in my locale } } 

Question: what did you do to get this aCurrentUTCCalendar ?

+5
source

Could the fact that it prints "Tue 5" and "Thu 6" indicate that you created the date?

ps: irrelevant, but instead doing cal.getTime (). getTime (), you can do cal.getTimeInMillis ()

+3
source

Source: https://habr.com/ru/post/1304766/


All Articles