Java.time API: Examples and Reference for Dealing with Date/Time on Java 8+

Last updated:

WIP Alert This is a work in progress. Current information is correct but more content will probably be added in the future.

All Examples are in Scala but they should be easy to translate to Java if need be

Format a ZonedDateTime according to a format String

You need to use java.time.format.DateTimeFormatter; you can use predefined constants like ISO_DATE or you can define you own pattern:

Using predefined patterns via constants:

import java.time._
import java.time.format._

// as of this posting
val zdt =
//res0: zdt: java.time.ZonedDateTime = 2016-04-01T02:07:22.549-03:00[America/Sao_Paulo]

// using useful constants in class DateTimeFormatter
// res1: String = 2016-04-01-03:00

Using custom patterns:

// using a custom string with .ofPattern()
//res2: String = 2016-04-01

Converting an epoch time into a ZonedDateTime object

Epoch time (also know as Unix time) is the number of seconds (or milliseconds) elapsed since 1 January, 1970. GMT

import java.time._

//using milliseconds

// refers to Mon, 29 Aug 2016 18:28:28.075 GMT
val millis = 1472495308075L
val asZdtMillis = Instant.ofEpochMilli(millis).atZone(ZoneId.of("UTC"))
//asZdtMillis: java.time.ZonedDateTime = 2016-08-29T18:28:28.075Z[UTC]
import java.time._

// using seconds

// refers to Mon, 29 Aug 2016 18:28:28 GMT
// (same date as above, without milliseconds)
val seconds = 1472495308L
val asZdtSeconds = Instant.ofEpochSecond(seconds).atZone(ZoneId.of("UTC"))
// java.time.ZonedDateTime = 2016-08-29T18:28:28Z[UTC]

Dialogue & Discussion