The java.util.Date class has no time zone assignedâ€ , yet it's
toString implementation confusingly applies the JVM's current default time zone.
Avoid java.util.Date & .Calendar
This is one of many reasons to avoid the notoriously troublesome java.util.Date, .Calendar, and SimpleDateFormat classes bundled with Java. Avoid them. Instead use either:
Some example code in Joda-Time 2.3 follows. Search StackOveflow for many more examples and much discussion.
DateTimeZone timeZoneLondon = DateTimeZone.forID( "Europe/London" );
DateTimeZone timeZoneKolkata = DateTimeZone.forID( "Asia/Kolkata" );
DateTimeZone timeZoneNewYork = DateTimeZone.forID( "America/New_York" );
DateTime nowLondon = DateTime.now( timeZoneLondon ); // Assign a time zone rather than rely on implicit default time zone.
DateTime nowKolkata = nowLondon.withZone( timeZoneKolkata );
DateTime nowNewYork = nowLondon.withZone( timeZoneNewYork );
DateTime nowUtc = nowLondon.withZone( DateTimeZone.UTC ); // Built-in constant for UTC.
We have four representations of the same moment in the timeline of the Universe.
Java 8 and later has a new java.time package built-in. This package was inspired by Joda-Time. While they share some similarities and class names, they are different; each has features the other lacks. One notable difference is that java.time avoids constructors, instead uses static instantiation methods.
In the case of this Question, they work in the same fashion. Specify a time zone, and call a
now method to get current moment, then create a new instance based on the old immutable instance to adjust for time zone.
Note the two different time zone classes. One is a named time zone including all the rules for Daylight Saving Time and other such anomalies plus an offset from UTC while the other is only the offset.
ZoneId zoneMontrÃ©al = ZoneId.of("America/Montreal");
ZonedDateTime nowMontrÃ©al = ZonedDateTime.now ( zoneMontrÃ©al );
ZoneId zoneTokyo = ZoneId.of("Asia/Tokyo");
ZonedDateTime nowTokyo = nowMontrÃ©al.withZoneSameInstant( zoneTokyo );
ZonedDateTime nowUtc = nowMontrÃ©al.withZoneSameInstant( ZoneOffset.UTC );
â€ Actually the
java.util.Date class does have a time zone buried within its source code. But the class ignores that time zone for most practical purposes. So, as shorthand, itâ€™s often said that j.u.Date has no time zone assigned. Confusing? Yes. Avoid the mess that is j.u.Date and go with Joda-Time and/or java.time.