Java.time API: Examples and Reference in Scala

Java.time API: Examples and Reference in Scala

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.

Format ZonedDateTime with 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 = ZonedDateTime.now()
//res0: zdt: java.time.ZonedDateTime = 2016-04-01T02:07:22.549-03:00[America/Sao_Paulo]

// using useful constants in class DateTimeFormatter
zdt.format(DateTimeFormatter.ISO_DATE)
// res1: String = 2016-04-01-03:00

Using custom patterns:

// using a custom string with .ofPattern()
zdt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
//res2: String = 2016-04-01

Epoch time to ZonedDateTime

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

String to LocalDate

Use LocalDate.parse(...)

import java.time.LocalDate

val date = LocalDate.parse("2021-01-29")
# res8: java.time.LocalDate = 2021-01-29

Today's Date

Use LocalDate.now()

import java.time.LocalDate

LocalDate.now()
# res8: java.time.LocalDate = 2022-11-25

LocalDate from String

As above, just use LocalDate.parse()

import java.time.LocalDate

val date = LocalDate.parse("2022-02-25")
# res8: java.time.LocalDate = 2021-02-25

Build LocalDate object

Use LocalDate.of(year, month, day)

import java.time.LocalDate

val date = LocalDate.of(2021,1,29)
# res8: java.time.LocalDate = 2021-01-29

LocalDate from year,month,day

Again, as above: just use LocalDate.of(year, month, day)

import java.time.LocalDate

val date = LocalDate.of(2022,2,25)
# res8: java.time.LocalDate = 2022-02-22

See also