Monday, July 11, 2016

java.time

java.time is a package for handling date / time values, introduced in Java 8. Before that you had to use classes like java.util.Date or java.sql.Date, if you were dealing with SQL databases.

These are still available in Java 8, but I would rather avoid them, as they're not thread safe, don't support the notion of time zones, etc. You can use a third-party solution like Joda-Time, but if you're writing Java 8 code, I see no reason not to use buiilt-in java.time.

Here's an article from Java Magazine, introducing java.time package.

I myself am most interested in ZonedDateTime class, as it represents timestamp in a certain time zone. ZonedDateTime (like OffsetDateTime class) contains at its heart an object of Instant class, and time zone information.

Instant is "an instantaneous point on the time-line", in other words it's just a number of seconds (and nanoseconds) passed since "epoch" (1970-01-01T00:00:00Z). This value doesn't depend on time zone, it is the same no matter where in the world you are (java.time doesn't take relativity into account, which is fine with me).

What this means, basically, is that you can't "convert" ZonedDateTime to another time zone, but what you can do instead is create another ZonedDateTime object with the same Instant value, but with different time zone setting. You can't change your existing ZonedDateTime objects, since they are immutable (thread safety!).

Using ZonedDateTime.withZoneSameInstant does just that:
import java.time.ZoneId;
import java.time.ZonedDateTime;

. . .

ZonedDateTime zdtHereNow = ZonedDateTime.now();
System.out.println("ZonedTimeDate here and now = " + zdtHereNow);

ZoneId utcTzId = ZoneId.of("UTC");
ZonedDateTime zdtUtcNow = zdtHereNow.withZoneSameInstant(utcTzId);
System.out.println("ZonedTimeDate \"here and now\" in UTC = " + zdtUtcNow);

No comments:

Post a Comment