Time Formatting Parsing in Scala

Scala supports time formatting and parsing via pattern-based layouts, similar to other programming languages.

import java.time.{Instant, ZonedDateTime, ZoneId}
import java.time.format.DateTimeFormatter

object TimeFormattingParsing {
  def main(args: Array[String]): Unit = {
    val p = println _

    // Here's a basic example of formatting a time
    // according to ISO_OFFSET_DATE_TIME, which is similar to RFC3339
    val now = ZonedDateTime.now()
    p(now.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME))

    // Time parsing uses the same formatter as formatting
    val t1 = ZonedDateTime.parse("2012-11-01T22:08:41+00:00", DateTimeFormatter.ISO_OFFSET_DATE_TIME)
    p(t1)

    // We can create custom formatters using pattern strings
    p(now.format(DateTimeFormatter.ofPattern("h:mma")))
    p(now.format(DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss yyyy")))
    p(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")))

    val customFormatter = DateTimeFormatter.ofPattern("h mm a")
    val t2 = LocalTime.parse("8 41 PM", customFormatter)
    p(t2)

    // For purely numeric representations you can also
    // use standard string formatting with the extracted
    // components of the time value
    printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
      now.getYear, now.getMonthValue, now.getDayOfMonth,
      now.getHour, now.getMinute, now.getSecond)

    // parse will throw an exception on malformed input
    try {
      val ansicFormatter = DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss yyyy")
      ZonedDateTime.parse("8:41PM", ansicFormatter)
    } catch {
      case e: Exception => p(e.getMessage)
    }
  }
}

In this Scala example, we use the java.time package, which provides a more modern and robust API for date and time manipulation compared to the older java.util.Date class.

We start by importing necessary classes from java.time and java.time.format packages.

The ZonedDateTime.now() method is used to get the current date and time, similar to time.Now() in Go.

For formatting and parsing, we use DateTimeFormatter. The ISO_OFFSET_DATE_TIME formatter is similar to RFC3339 used in the Go example.

Custom formatters can be created using DateTimeFormatter.ofPattern(). The pattern strings are different from Go, but serve a similar purpose.

For purely numeric formatting, we can use Scala’s string interpolation or printf method, extracting individual components from the ZonedDateTime object.

Error handling in Scala is typically done using try-catch blocks, as shown in the last example where we attempt to parse an incorrectly formatted string.

When you run this program, you’ll see output similar to the following:

2023-05-15T10:30:15.161182+01:00
2012-11-01T22:08:41Z
10:30AM
Mon May 15 10:30:15 2023
2023-05-15T10:30:15.161+01:00
10:41
2023-05-15T10:30:15-00:00
Text '8:41PM' could not be parsed at index 0

Note that the exact output will depend on your current time and timezone.