Scala Convert Date to Epoch

1. Introduction

Converting a date to an epoch time, which is the number of seconds or milliseconds since January 1, 1970 (UTC), is a common task in Scala, especially when dealing with timestamps and date-time manipulations. Scala can leverage Java's date-time libraries for this purpose. In this blog post, we'll explore how to convert a date to epoch time in Scala.

2. Program Steps

1. Import Java's date-time classes.

2. Define a date.

3. Convert the date to epoch time in seconds and milliseconds.

4. Print the results to verify the conversion.

5. Execute the code to observe the conversion from date to epoch time.

3. Code Program

import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter

object DateToEpochDemo extends App {
  val dateString = "2021-12-01"
  val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
  val localDate = LocalDate.parse(dateString, formatter)

  // Convert LocalDate to epoch time
  val epochSeconds = localDate.atStartOfDay(ZoneId.of("UTC")).toEpochSecond
  val epochMillis = localDate.atStartOfDay(ZoneId.of("UTC")).toInstant.toEpochMilli

  println(s"Epoch time in seconds: $epochSeconds")
  println(s"Epoch time in milliseconds: $epochMillis")
}

Output:

Epoch time in seconds: 1638316800
Epoch time in milliseconds: 1638316800000

Explanation:

1. LocalDate.parse is used to convert a string to a LocalDate object based on the provided date format.

2. atStartOfDay(ZoneId.of("UTC")) converts the LocalDate to a ZonedDateTime at the start of the day in UTC.

3. toEpochSecond and toInstant.toEpochMilli are used to convert the ZonedDateTime to epoch time in seconds and milliseconds, respectively.

4. The epoch time represents the number of seconds/milliseconds since January 1, 1970, 00:00:00 UTC.


Comments