Search code examples
javazoneddatetime

Java - Result when compare two ZonedDateTime is not as expected


I have this code :

ZonedDateTime t1 = ZonedDateTime.parse("2018-04-06T10:01:00.000+03:00");
ZonedDateTime t2 = ZonedDateTime.parse("2018-04-06T10:01:00.000-03:00");
System.out.println(t1.compareTo(t2));

The result is -1. I guess it will convert both t1 and t2 to the same timezone then compare it. E.g in the first case it will (maybe) compare

t1 = 2018-04-06T07:01:00.000+00:00 to t2 = 2018-04-06T13:01:00.000+00:00

This case return 1 as I expected

ZonedDateTime t1 = ZonedDateTime.parse("2018-04-06T17:01:00.000+03:00");
ZonedDateTime t2 = ZonedDateTime.parse("2018-04-06T10:01:00.000-03:00");
System.out.println(t1.compareTo(t2));

But this one (*) doesn't return 0, it return 1 :

ZonedDateTime t1 = ZonedDateTime.parse("2018-04-06T16:01:00.000+03:00");
ZonedDateTime t2 = ZonedDateTime.parse("2018-04-06T10:01:00.000-03:00");
System.out.println(t1.compareTo(t2));

I even try to use truncatedTo(ChronoUnit.MINUTES) after parse the string to ignore the seconds part but nothing change.

The most interested thing is if I decrease / increase t1 / t2 by one second, the result will be -1

e.g :

ZonedDateTime t1 = ZonedDateTime.parse("2018-04-06T16:01:00.000+03:00");
ZonedDateTime t2 = ZonedDateTime.parse("2018-04-06T10:01:01.000-03:00");
System.out.println(t1.compareTo(t2));

In my use case, all user input time will be saved in the above format in many ZoneOffset and I have some query where I need to compare it with server time (ignore the seconds of the time). How can I get t1 equals t2 in case (*) above?


Solution

  • Use toInstant(), then compare the results, like so:

        ZonedDateTime t1 = ZonedDateTime.parse("2018-04-06T16:01:00.000+03:00");
        ZonedDateTime t2 = ZonedDateTime.parse("2018-04-06T10:01:00.000-03:00");
        System.out.println(t1.toInstant().compareTo(t2.toInstant()));