Instant
A moment in time.
A point in time must be uniquely identified in a way that is independent of a time zone. For example, 1970-01-01, 00:00:00
does not represent a moment in time since this would happen at different times in different time zones: someone in Tokyo would think it is already 1970-01-01
several hours earlier than someone in Berlin would. To represent such entities, use LocalDateTime. In contrast, "the moment the clocks in London first showed 00:00 on Jan 1, 2000" is a specific moment in time, as is "1970-01-01, 00:00:00 UTC+0", so it can be represented as an Instant.
Instant
uses the UTC-SLS (smeared leap second) time scale. This time scale doesn't contain instants corresponding to leap seconds, but instead "smears" positive and negative leap seconds among the last 1000 seconds of the day when a leap second happens.
Obtaining the current moment
The Clock interface is the primary way to obtain the current moment:
val clock: Clock = Clock.System
val instant = clock.now()
The Clock.System implementation uses the platform-specific system clock to obtain the current moment. Note that this clock is not guaranteed to be monotonic, and the user or the system may adjust it at any time, so it should not be used for measuring time intervals. For that, consider using TimeSource.Monotonic and TimeMark instead of Clock.System and Instant.
Obtaining human-readable representations
Date and time
Instant is essentially the number of seconds and nanoseconds since a designated moment in time, stored as something like 1709898983.123456789
. Instant does not contain information about the day or time, as this depends on the time zone. To work with this information for a specific time zone, obtain a LocalDateTime using Instant.toLocalDateTime:
val instant = Instant.fromEpochSeconds(1709898983, 123456789)
instant.toLocalDateTime(TimeZone.of("Europe/Berlin")) // 2024-03-08T12:56:23.123456789
instant.toLocalDateTime(TimeZone.UTC) // 2024-03-08T11:56:23.123456789
For values very far in the past or the future, this conversion may fail. The specific range of values that can be converted to LocalDateTime is platform-specific, but at least DISTANT_PAST, DISTANT_FUTURE, and all values between them can be converted to LocalDateTime.
Date or time separately
To obtain a LocalDate or LocalTime, first, obtain a LocalDateTime, and then use its LocalDateTime.date and LocalDateTime.time properties:
val instant = Instant.fromEpochSeconds(1709898983, 123456789)
instant.toLocalDateTime(TimeZone.of("Europe/Berlin")).date // 2024-03-08
Arithmetic operations
Elapsed-time-based
The plus and minus operators can be used to add Durations to and subtract them from an Instant:
Clock.System.now() + 5.seconds // 5 seconds from now
Durations can also be represented as multiples of some time-based datetime unit:
Clock.System.now().plus(4, DateTimeUnit.HOUR) // 4 hours from now
Also, there is a minus operator that returns the Duration representing the difference between two instants:
val start = Clock.System.now()
val concertStart = LocalDateTime(2023, 1, 1, 20, 0, 0).toInstant(TimeZone.of("Europe/Berlin"))
val timeUntilConcert = concertStart - start
Calendar-based
Since Instant represents a point in time, it is always well-defined what the result of arithmetic operations on it is, including the cases when a calendar is used. This is not the case for LocalDateTime, where the result of arithmetic operations depends on the time zone. See the LocalDateTime documentation for more details.
Adding and subtracting calendar-based units can be done using the plus and minus operators, requiring a TimeZone:
// One day from now in Berlin
Clock.System.now().plus(1, DateTimeUnit.DAY, TimeZone.of("Europe/Berlin"))
// A day and two hours short from two months later in Berlin
Clock.System.now().plus(DateTimePeriod(months = 2, days = -1, hours = -2), TimeZone.of("Europe/Berlin"))
The difference between Instant values in terms of calendar-based units can be obtained using the periodUntil method:
val start = Clock.System.now()
val concertStart = LocalDateTime(2023, 1, 1, 20, 0, 0).toInstant(TimeZone.of("Europe/Berlin"))
val timeUntilConcert = start.periodUntil(concertStart, TimeZone.of("Europe/Berlin"))
// Two months, three days, four hours, and five minutes until the concert
Or the Instant.until method, as well as Instant.daysUntil, Instant.monthsUntil, and Instant.yearsUntil extension functions:
val start = Clock.System.now()
val concertStart = LocalDateTime(2023, 1, 1, 20, 0, 0).toInstant(TimeZone.of("Europe/Berlin"))
val timeUntilConcert = start.until(concertStart, DateTimeUnit.DAY, TimeZone.of("Europe/Berlin"))
// 63 days until the concert, rounded down
Platform specifics
On the JVM, there are Instant.toJavaInstant()
and java.time.Instant.toKotlinInstant()
extension functions to convert between kotlinx.datetime
and java.time
objects used for the same purpose. Similarly, on the Darwin platforms, there are Instant.toNSDate()
and NSDate.toKotlinInstant()
extension functions.
Construction, serialization, and deserialization
fromEpochSeconds can be used to construct an instant from the number of seconds since 1970-01-01T00:00:00Z
(the Unix epoch). epochSeconds and nanosecondsOfSecond can be used to obtain the number of seconds and nanoseconds since the epoch.
val instant = Instant.fromEpochSeconds(1709898983, 123456789)
instant.epochSeconds // 1709898983
instant.nanosecondsOfSecond // 123456789
fromEpochMilliseconds allows constructing an instant from the number of milliseconds since the epoch. toEpochMilliseconds can be used to obtain the number of milliseconds since the epoch. Note that Instant supports nanosecond precision, so converting to milliseconds is a lossy operation.
val instant1 = Instant.fromEpochSeconds(1709898983, 123456789)
instant1.nanosecondsOfSecond // 123456789
val milliseconds = instant1.toEpochMilliseconds() // 1709898983123
val instant2 = Instant.fromEpochMilliseconds(milliseconds)
instant2.nanosecondsOfSecond // 123000000
parse and toString methods can be used to obtain an Instant from and convert it to a string in the ISO 8601 extended format.
val instant = Instant.parse("2023-01-02T22:35:01+01:00")
instant.toString() // 2023-01-02T21:35:01Z
During parsing, the UTC offset is not returned separately. If the UTC offset is important, use DateTimeComponents with DateTimeComponents.Formats.ISO_DATE_TIME_OFFSET to parse the string instead.
Instant.parse and Instant.format also accept custom formats:
val customFormat = DateTimeComponents.Format {
date(LocalDate.Formats.ISO)
char(' ')
time(LocalTime.Formats.ISO)
char(' ')
offset(UtcOffset.Formats.ISO)
}
val instant = Instant.parse("2023-01-02 22:35:01.14 +01:00", customFormat)
instant.format(customFormat, offset = UtcOffset(hours = 2)) // 2023-01-02 23:35:01.14 +02:00
Additionally, there are several kotlinx-serialization
serializers for Instant:
InstantIso8601Serializer for the ISO 8601 extended format.
InstantComponentSerializer for an object with components.
See also
for a user-visible representation of moments in time in an unspecified time zone.
Types
Properties
Returns true if the instant is Instant.DISTANT_FUTURE or later.
Returns true if the instant is Instant.DISTANT_PAST or earlier.
Functions
Compares this
instant with the other instant. Returns zero if this instant represents the same moment as the other (meaning they are equal to one another), a negative number if this instant is earlier than the other, and a positive number if this instant is later than the other.
Returns an instant that is the result of subtracting the value number of the specified unit from this instant.
Returns an instant that is the result of subtracting components of DateTimePeriod from this instant. The components are subtracted in the order from the largest units to the smallest, i.e., from years to nanoseconds.
Returns a DateTimePeriod representing the difference between other and this
instants.
Returns an instant that is the result of adding the value number of the specified unit to this instant.
Returns an instant that is the result of adding components of DateTimePeriod to this instant. The components are added in the order from the largest units to the smallest, i.e., from years to nanoseconds.
Returns the number of milliseconds from the epoch instant 1970-01-01T00:00:00Z
.
Converts this kotlinx.datetime.Instant value to a java.time.Instant value.