These are some examples of how to use the new java.time API in Java 8, especifically timezones, which are often a source of confusion.

This notebook supports the following blog post: Java 8 Timezones: Examples in Scala

In [1]:
import java.time._
import java.time._
In [2]:
ZonedDateTime.now()
res1: ZonedDateTime = 2016-03-08T23:37:40.366-03:00[America/Sao_Paulo]

Represent a LocalDateTime in a specific time zone

LocalDateTimes do not know what time zone they're in

In [3]:
val ldt = LocalDateTime.of(2015,10,15,4,12,30)
ldt: LocalDateTime = 2015-10-15T04:12:30
In [4]:
val zone = ZoneId.of("-03:00")
zone: ZoneId = -03:00
In [5]:
ldt.atZone(zone)
res4: ZonedDateTime = 2015-10-15T04:12:30-03:00

Change the time zone for a ZonedDateTime object

One instant can be represented in many ways, i.e. time zones

In [6]:
val frTz = ZoneId.of("Europe/Paris")
frTz: ZoneId = Europe/Paris
In [7]:
val ausTz = ZoneId.of("Australia/Sydney")
ausTz: ZoneId = Australia/Sydney
In [8]:
val time = LocalDateTime.of(2015,5,2,5,30,0)
time: LocalDateTime = 2015-05-02T05:30
In [9]:
val ausTime = time.atZone(ausTz)
ausTime: ZonedDateTime = 2015-05-02T05:30+10:00[Australia/Sydney]
In [10]:
val frTime = ausTime.withZoneSameInstant(frTz).toLocalDateTime
frTime: LocalDateTime = 2015-05-01T21:30

Represent a LocalTime in a given time zone

LocalTimes are like LocalDateTimes but without information about what day it is

In [11]:
val tz = ZoneId.of("Europe/Zurich")
tz: ZoneId = Europe/Zurich
In [12]:
val lt = LocalTime.of(4,12,20)
lt: LocalTime = 04:12:20
In [13]:
val offset = tz.getRules.getOffset(Instant.now)
offset: ZoneOffset = +01:00
In [14]:
lt.atOffset(offset)
res13: OffsetTime = 04:12:20+01:00

Get the current date and time in UTC

In [15]:
val now = Instant.now
now: Instant = 2015-12-24T14:19:33.239Z
In [16]:
val utcTz = ZoneId.of("UTC")
utcTz: ZoneId = UTC
In [17]:
now.atZone(utcTz)
res16: ZonedDateTime = 2015-12-24T14:19:33.239Z[UTC]