1

If I compare two DateTime with two different time zone, there is a problem, or I should make him in the same time zone ?

Example :

DateTimeZone a = new DateTimeZone("Pacific/Kiritimati");
    DateTimeZone b = new DateTimeZone("Pacific/Gambier");

    DateTime dateOne = new DateTime(a);
    DateTime dateTwo = new DateTime(b);

    if (dateOne.compareTO(dateTwo) == 0) {
        // yes
    } else {
        // no
    }

Thnak you. (sorry for my bad english)

Andromed
  • 31
  • 1
  • 6
  • You decide how to compare. In principle there are two criterions with such timestamps (which are local and global). Either you compare the instants (on global timeline) or you only compare the local timestamps associated with disregarding the timezone. Whatever you decide it must fit your concrete use-case. The `compareTo()`-method you use only compares the instants, not the local timestamp representations. Maybe this is sufficient for you. – Meno Hochschild Jun 10 '15 at 10:03
  • 1
    IMPORTANT: If you want to compare two instants using the expression `dateOne.compareTO(dateTwo) == 0` then you might experience it to be almost always `false` because a `DateTime` can have a time portion down to milliseconds. This is especially true if the source of your `DateTime`-objects is a clock (which usually emits different milliseconds). – Meno Hochschild Jun 10 '15 at 14:32
  • FYI, the [Joda-Time](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), with the team advising migration to the [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jun 15 '17 at 04:29

2 Answers2

3

People always have confusion about dates and timezones. A date (or a time, or datetime) is a specific instant in time. This instant is the same in all the Universe, so it is independent from timezone, and it is usually represented as UTC (Universal Time) or Z (Zulu time). Timzone is a modification of UTC to show relative solar time for this specific zone in Earth. By setting the timezone, you're just telling that this datetime is relative to this specific timezone, but internally it will be still represented as UTC. In this case, they should be different if the timezones have a different UTC offset.

m0skit0
  • 25,268
  • 11
  • 79
  • 127
  • Hm, I cannot follow - as far as Joda-Time is concerned. The type `DateTime` is more than just an instant. It also has a reference to a specific timezone, not just UTC. So it also knows a local/zonal representation. That is the main reason why its `compareTo()`-method is inconsistent with `equals()`. And by the way: In Joda-Time there are types like `LocalDate` (a pure calendar date) which are NOT instants. – Meno Hochschild Jun 10 '15 at 10:40
  • Yes, I know. Still the time is still stored as UTC and compared as such, timezone is irrelevant. What I mean is that 10:00 GMT is the same as 11:00 GMT+1. I know about `LocalDate` but I don't see what it has to do with the question. – m0skit0 Jun 10 '15 at 11:58
  • I only mentioned `LocalDate` as counter example because of your statement: " A date (or a time, or datetime) is a specific instant in time." And else we talk about the type `DateTime` here which is more than just an instant. – Meno Hochschild Jun 10 '15 at 12:20
  • "A date (or a time, or datetime)" is not a **local** date/time. And no, you're wrong, `DateTime` precisely represents an insant of time: "it represents **an exact point on the time-line**". [Read the documentation](http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html). As I said: people always have confusion about dates and timezones but in fact it is quite simple if you think about it the right way. – m0skit0 Jun 10 '15 at 13:36
  • ;-) I insist that your statement "A date (or a time, or datetime) is a specific instant in time" is simply not clear. While I agree that `java.util.Date` is an instant I disagree in context of Joda-Time since the terms date and time are referring to the local date and time in common understanding. And about Joda class `DateTime`, I have not argued that it is not an instant, but I say it is more than an instant only. It also refers to a timezone and has an extra local timestamp representation beyond being just an instant. Note that Joda-Time has several implementations of `ReadableInstant`. – Meno Hochschild Jun 10 '15 at 13:57
  • If we only want/talk about a pure instant then the class `org.joda.time.Instant` is the right type. It has just the global timeline and nothing else - no reference to a local representation. The type `DateTime` is very different in this detail although it is an instant, too. – Meno Hochschild Jun 10 '15 at 14:02
  • What I mean is that if you're going to compare 2 datetimes, which is the question being asked here, the location where the time measurement was done is totally irrelevant, as the timezone refers to the geographical location where the time measurement was done. You cannot compare times with the timezone applied, you need to compare as UTC, so for all purposes, the timezone is irrelevant to the question being asked. – m0skit0 Jun 10 '15 at 14:12
  • 2
    Consider the question when two people in New York and Paris wake up and who wakes up first. Here a comparison using the local timestamps instead of the instants is a valid option (of course, usually Paris is earlier on the global timeline but we can also have another perspective relative to the start of the local day). The right answer depends on the use-case of the OP. And that is what I tried to express with my comment directed to the OP. If he wants an instant comparison then his code is fine with the exception that he should not use the operator ==. – Meno Hochschild Jun 10 '15 at 14:35
2

Using java.time

The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.

You can indeed compare date-time objects of different time zones. Internally the moment is calculated as a number of seconds (plus fractional second) since the epoch of 1970-01-01T00:00:00Z. While the wall-clock time appears differently per the assigned time zone, think of their underlying meaning being a point on the timeline in UTC. Therefore any pair of date-time objects can easily be compared.

In java.time we use the ZonedDateTime for this work. This class offers isEqual, isBefore, and isAfter methods for comparison.

ZoneId zP_K = ZoneId.of( "Pacific/Kiritimati" ) ;
ZoneId zP_G = ZoneId.of( "Pacific/Gambier" ) ;

Instant instant = Instant.now() ;  // Current moment in UTC, with resolution up to nanoseconds.

ZonedDateTime zdtP_K = instant.atZone( zP_K ) ;
ZonedDateTime zdtP_G = instant.atZone( zP_G ) ;

Boolean sameMoment = zdtP_K.isEqual( zdtP_G ) ; // Or `isBefore` or `isAfter`.

See this code run live at IdeOne.com.

instant.toString(): 2017-06-15T12:53:35.276Z

zdtP_K.toString(): 2017-06-16T02:53:35.276+14:00[Pacific/Kiritimati]

zdtP_G.toString(): 2017-06-15T03:53:35.276-09:00[Pacific/Gambier]

sameMoment: true

Tip: Do most of your thinking, your business logic, your logging, and your data exchange/storage all in UTC. Think of UTC as The One True Time™ with other zones being mere variations. Apply a time zone only where required by the business logic or for presentation to the user. Forget about your own parochial time zone while wearing your Programmer At Work hat.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154