Time in Groovy

Our first program will demonstrate how to work with time and durations in Groovy. Here’s the full source code:

import java.time.*

def p = { println it }

// We'll start by getting the current time.
def now = Instant.now()
p(now)

// You can build a time instance by providing the
// year, month, day, etc. Times are always associated
// with a ZoneId, i.e. time zone.
def then = ZonedDateTime.of(2009, 11, 17, 20, 34, 58, 651387237, ZoneId.of("UTC"))
p(then)

// You can extract the various components of the time
// value as expected.
p(then.year)
p(then.month)
p(then.dayOfMonth)
p(then.hour)
p(then.minute)
p(then.second)
p(then.nano)
p(then.zone)

// The Monday-Sunday DayOfWeek is also available.
p(then.dayOfWeek)

// These methods compare two times, testing if the
// first occurs before, after, or at the same time
// as the second, respectively.
p(then.isBefore(now.atZone(ZoneId.of("UTC"))))
p(then.isAfter(now.atZone(ZoneId.of("UTC"))))
p(then.isEqual(now.atZone(ZoneId.of("UTC"))))

// The Duration class represents the interval between two times.
def diff = Duration.between(then.toInstant(), now)
p(diff)

// We can compute the length of the duration in
// various units.
p(diff.toHours())
p(diff.toMinutes())
p(diff.getSeconds())
p(diff.toNanos())

// You can use plus to advance a time by a given
// duration, or with a minus to move backwards by a
// duration.
p(then.plus(diff))
p(then.minus(diff))

To run the program, save it as TimeExample.groovy and use the groovy command:

$ groovy TimeExample.groovy
2023-05-24T12:34:56.789Z
2009-11-17T20:34:58.651387237Z[UTC]
2009
NOVEMBER
17
20
34
58
651387237
UTC
TUESDAY
true
false
false
PT118046H0M1.137612763S
118046
7082760
25497761
25497761137612763
2023-05-24T22:34:59.789Z[UTC]
1996-05-13T18:34:57.513774474Z[UTC]

This example demonstrates how to work with time and durations in Groovy using the Java 8 Time API. It covers creating time instances, extracting components, comparing times, calculating durations, and performing time arithmetic.

Groovy leverages Java’s powerful time and date API, making it easy to work with time-related operations. The java.time package provides a comprehensive set of classes for handling dates, times, and durations with precision and flexibility.