Time in Kotlin

Kotlin offers extensive support for times and durations; here are some examples.

import java.time.*
import java.time.temporal.ChronoUnit

fun main() {
    // We'll start by getting the current time.
    val now = Instant.now()
    println(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.
    val then = ZonedDateTime.of(2009, 11, 17, 20, 34, 58, 651387237, ZoneId.of("UTC"))
    println(then)

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

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

    // These methods compare two times, testing if the
    // first occurs before, after, or at the same time
    // as the second, respectively.
    println(then.isBefore(ZonedDateTime.now()))
    println(then.isAfter(ZonedDateTime.now()))
    println(then.isEqual(ZonedDateTime.now()))

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

    // We can compute the length of the duration in
    // various units.
    println(diff.toHours())
    println(diff.toMinutes())
    println(diff.seconds)
    println(diff.nano)

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

To run the program, save it as TimeExample.kt and use kotlinc to compile and kotlin to run:

$ kotlinc TimeExample.kt -include-runtime -d TimeExample.jar
$ kotlin TimeExample.jar
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
PT118046H0M58.137612763S
118046
7082760
25497658
137612763
2023-05-24T12:34:58.651387237Z[UTC]
1996-05-12T04:34:58.651387237Z[UTC]

This Kotlin code demonstrates various operations with dates and times, including creating time instances, extracting components, comparing times, calculating durations, and performing arithmetic with times and durations.

Next, we’ll look at the related idea of time relative to the Unix epoch.