Java.time API: Examples and Reference

Last updated:
Table of Contents

Starting with Java 8, the old JodaTime library for dates has been sort of merged into the main Java standard library.

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

Format ZonedDateTime according to 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

Convert epoch time into 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]

LocalDate to SQL Date

Use Date.valueOf(localdate.toString):

import java.time.LocalDate
import java.sql.Date

val ld = LocalDate.of(2019,12,1)

val sqlDate = Date.valueOf(ld.toString)
// Date = 2019-12-01

SQL Date to LocalDate

Simply use sqlDate.toLocalDate

import java.time.LocalDate
import java.sql.Date

val sqlDate = Date.valueOf("2019-12-01")

val ld = sqlDate.toLocalDate
// LocalDate = 2019-12-01

See also

Dialogue & Discussion