Scala supports time formatting and parsing via pattern-based layouts, similar to other programming languages.
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:
Note that the exact output will depend on your current time and timezone.