Time Formatting Parsing in Groovy
Groovy supports time formatting and parsing via pattern-based layouts.
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
def p = { println it }
// Here's a basic example of formatting a time
// according to ISO_DATE_TIME, which is similar to RFC3339
def t = LocalDateTime.now()
p(t.format(DateTimeFormatter.ISO_DATE_TIME))
// Time parsing uses the same layout values as format
def t1 = LocalDateTime.parse("2012-11-01T22:08:41", DateTimeFormatter.ISO_DATE_TIME)
p(t1)
// format and parse use example-based layouts. You can also
// supply custom layouts. Layouts must use the pattern letters
// defined in DateTimeFormatter documentation.
p(t.format(DateTimeFormatter.ofPattern("h:mma")))
p(t.format(DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss yyyy")))
p(t.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")))
def form = "h mm a"
def t2 = LocalDateTime.parse("8 41 PM", DateTimeFormatter.ofPattern(form))
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",
t.year, t.monthValue, t.dayOfMonth,
t.hour, t.minute, t.second)
// parse will throw an exception on malformed input
// explaining the parsing problem.
try {
LocalDateTime.parse("8:41PM", DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss yyyy"))
} catch (Exception e) {
p(e.message)
}
This Groovy code demonstrates time formatting and parsing, similar to the original example. Here are some key differences and explanations:
Groovy uses
java.time
classes, which are more modern than thejava.util.Date
class.Instead of
time.Now()
, we useLocalDateTime.now()
.The
RFC3339
format is replaced withISO_DATE_TIME
, which is very similar.Custom format strings use different syntax. Instead of Go’s reference time, Groovy uses pattern letters defined in the
DateTimeFormatter
documentation.Error handling is done with a try-catch block instead of returning an error value.
The
Printf
method is available in Groovy, allowing for similar string formatting as in the original example.
When you run this script, you’ll see output similar to the following:
2023-06-15T10:30:15.161182
2012-11-01T22:08:41
10:30AM
Thu Jun 15 10:30:15 2023
2023-06-15T10:30:15.161-07:00
2023-06-15T20:41
2023-06-15T10:30:15-00:00
Text '8:41PM' could not be parsed at index 0
The exact times will vary based on when you run the script.