logo

Scala - DateTime

Last Updated: 2021-11-19

Scala does not have a datetime package, but we can use the ones provided by Java.

Java 8+

Java 8 provides a better data/time API, so 3rd-party libraries like Joda-Time is no longer required.

Import

The date object is java.time.LocalDate, while the formatter is java.time.format.DateTimeFormatter

scala> import java.time.LocalDate
import java.time.LocalDate

scala> import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatter

Parse: String to Date

scala> val date = LocalDate.parse("01/01/2020", DateTimeFormatter.ofPattern("MM/dd/yyyy"))
date: java.time.LocalDate = 2020-01-01

Formatting: Date to String

Internally it is using ISO format

scala> print(date.toString)
2020-01-01

To specify the format, use another DateTimeFormatter

scala> date.format(DateTimeFormatter.ofPattern("yyyy.MM.dd"))
res0: String = 2020.01.01

Java 7

Use SimpleDateFormat to define format

scala> val originFormat = new SimpleDateFormat("ddMMMyyyy")
originFormat: java.text.SimpleDateFormat = java.text.SimpleDateFormat@efcbc5ed


scala> val targetFormat = new SimpleDateFormat("yyyy-MM-dd")
targetFormat: java.text.SimpleDateFormat = java.text.SimpleDateFormat@f67a0200

scala> targetFormat.format(originFormat.parse("01NOV2020"))
res3: String = 2020-11-01

Checkout more on date format:

http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html