Skip to content
Tutorials Center
My learning

Topics

Lesson 87 of 134 ยท Text, Files and Time

Dates, Times and Durations

Learn time in Kotlin - kotlin.time Duration, measureTime, TimeSource and TestTimeSource, plus java.time LocalDate, LocalDateTime, Instant, ZonedDateTime, Period, formatting and parsing.

Time looks easy until you write code for it. A day is not always 24 hours (daylight saving), a month has between 28 and 31 days, the same instant is a different clock time in Tokyo and in Lima, and a computer's clock can jump backwards when it is corrected. Two kinds of questions hide behind the word "time", and mixing them up causes most bugs:

  1. How long did something take? (an amount of time, measured with a steady clock)
  2. What does the calendar say? (a date or a clock time, interpreted in some time zone)

Kotlin answers the first with kotlin.time: Duration and time sources. For the second, the standard library does not (yet) bring a full calendar to the table, but you have the JDK's excellent java.time package, which is what Kotlin code uses on the JVM. This lesson covers both.

Duration: an amount of time

A Duration is a length of time, not a point on the calendar. You create it with extension properties on numbers: 5.seconds, 250.milliseconds, 1.5.hours, 2.days. Durations can be added, subtracted, multiplied by numbers and compared; toString() picks a readable form.

Kotlin Creating and combining durations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The toString() form is compact: 1m 30s, 8h 30m, 250ms, 1.5s. A Duration is a value class around a single number, so creating and passing them is cheap, and it knows its units: the compiler will never let you add seconds to a plain Int by accident, which is the classic "was that milliseconds or seconds?" bug. Prefer Duration over Long timeoutMillis in your APIs; the call site then reads timeout = 30.seconds.

A Duration has a fixed length. It has no calendar knowledge, so 1.days means exactly 24 hours, not "tomorrow at the same time". For "one calendar day later" use java.time (below).

Breaking a Duration into parts

toComponents splits a duration into days, hours, minutes, seconds and nanoseconds so you can format it yourself. inWholeX properties truncate, and Duration.parse reads text such as 1h 30m, PT2H15M (the ISO form) or 45s.

Kotlin toComponents and Duration.parse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

toComponents takes a lambda whose parameters are the parts; the version with four parameters gives total hours (not capped at 24), minutes, seconds and nanoseconds. Duration.parseOrNull returns null for bad text, while Duration.parse throws IllegalArgumentException. And notice that inWholeSeconds of 1999 ms is 1: it truncates.

Measuring how long code takes

measureTime { } runs a block and returns how long it took. measureTimedValue { } also returns the block's result. Both use a monotonic clock, a clock that only goes forward and is unaffected by someone setting the wall clock, which is exactly what you need for timing.

Kotlin measureTime and measureTimedValue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Real timings vary from run to run and machine to machine, so tests and examples should compare against bounds (as above) and never against an exact number. For serious benchmarking, a single measureTime is misleading: the JVM compiles hot code while it runs, so the first call is slower than later ones. Run the code many times first ("warm-up") or use a benchmarking tool such as JMH.

Time sources and marks

Behind measureTime is the TimeSource interface. TimeSource.Monotonic.markNow() returns a mark, and mark.elapsedNow() tells you the time since then. A mark can also be moved: mark + 10.seconds is a mark in the future, and hasPassedNow() tells you if it has arrived, which makes deadlines and timeouts easy.

TestTimeSource is a clock you control by hand. It is the right tool for testing time-dependent logic without sleeping, and it makes outputs deterministic.

Kotlin Marks, deadlines and TestTimeSource

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The cache never touches the real clock: the test clock moves with +=, so the test runs instantly and gives the same answer every time. In production you would pass TimeSource.Monotonic instead. Taking the clock as a constructor parameter is the design trick that makes time-based code testable.

java.time: calendars, dates and zones

For dates on the calendar, use the JDK's java.time package (the types are immutable and thread-safe). The key types:

Type Represents Example
LocalDate a date without time or zone 2026-03-09
LocalTime a clock time without date or zone 14:30
LocalDateTime date and time, no zone 2026-03-09T14:30
Instant a point on the global timeline (UTC) 2026-03-09T14:30:00Z
ZonedDateTime date, time and a time zone 2026-03-09T14:30+01:00[Europe/Paris]
Period a calendar amount: years, months, days 1 month, 2 days

Local... types have no time zone at all, so they cannot name a moment: "March 9 at 14:30" is a different instant in each city. Use them for things like birthdays and opening hours. Use Instant (or ZonedDateTime) when you mean an exact moment, such as a log entry or a payment.

Kotlin LocalDate basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice 2026-01-31 plus one month is the last valid day of February, and 2024-02-29 plus one year lands on 2025-02-28: the library clamps to the end of the month instead of failing. All arithmetic returns a new object; date.plusDays(30) on its own as a statement does nothing. Invalid dates fail early: LocalDate.of(2026, 2, 30) throws DateTimeException. Because LocalDate implements Comparable, Kotlin's < and > operators work on it.

Times, LocalDateTime and Instants

LocalDateTime combines date and time. Instant is the machine view: a count of time since 1970-01-01T00:00:00Z. Convert between the local view and an instant only by naming a time zone.

Kotlin LocalDateTime, Instant and ZonedDateTime

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The same instant shows as 15:30 in Paris (UTC+1 in March, before the clocks change) and 23:30 in Tokyo. Because the two ZonedDateTimes name the same instant, their toInstant() values are equal. java.time.Duration and kotlin.time.Duration are different types: import one under an alias as above, and convert with toKotlinDuration() and toJavaDuration() from kotlin.time.

Daylight saving makes a "day" vary. Adding Period.ofDays(1) or plusDays(1) to a ZonedDateTime keeps the same clock time (so the real elapsed time might be 23 or 25 hours), while adding 24.hours (a Duration) adds exactly 24 elapsed hours. Choose according to your meaning: "same time tomorrow" versus "24 hours later".

Formatting and parsing

DateTimeFormatter turns dates into strings and back. Use ofPattern with letters: yyyy year, MM month number, MMM short month name, dd day, HH hour (24-hour), mm minutes, EEEE weekday name. Always pass a Locale, otherwise names of months follow the machine's language and output differs between computers.

Kotlin DateTimeFormatter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The ISO format (2026-03-09) is the one to use for storing and exchanging dates, because it sorts correctly as text and every system understands it. Patterns for people (MM/dd/yyyy versus dd.MM.yyyy) are for display only. Mind the case of letters: MM is the month, mm is the minute, and hh is the 12-hour clock while HH is 24-hour; mixing these up is a classic mistake. LocalDate.parse throws DateTimeParseException on bad text, with a message that shows exactly where it failed; the failing call above is 2026-02-30, a date that does not exist.

Choosing the right type

  • How long? kotlin.time.Duration. Use measureTime, TimeSource.Monotonic, and TestTimeSource for tests.
  • A calendar date with no time of day (birthday, due date): LocalDate.
  • A moment that happened or will happen (log line, order time): Instant; store it in UTC.
  • What to show a user in their city: ZonedDateTime (or Instant.atZone(zone)) and a DateTimeFormatter with a Locale.
  • Calendar amounts (3 months): Period; exact elapsed time (36 hours): Duration.
  • Never use the legacy java.util.Date and Calendar in new code, and avoid System.currentTimeMillis() for measuring elapsed time, because the wall clock can change; use a monotonic source.
  • Do not print "now" in tests. Accept a clock (java.time.Clock or a TimeSource) as a parameter and fix it in tests.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is 90.seconds == 1.5.minutes?

    A Duration stores a length of time independently of the unit it was created with, so equal lengths compare equal.
  2. 2. Why use TimeSource.Monotonic (or measureTime) instead of System.currentTimeMillis() to measure elapsed time?

    A monotonic clock only moves forward and ignores clock adjustments, which is what elapsed-time measurement needs.
  3. 3. What is the result of LocalDate.of(2026, 1, 31).plusMonths(1)?

    java.time clamps to the last valid day of the target month, so the answer is 2026-02-28.
  4. 4. A payment is recorded at the exact moment it happened. Which type should store it?

    An Instant identifies a point on the global timeline. LocalDateTime has no time zone, so it does not name one moment.
  5. 5. Why is a TestTimeSource useful?

    Inject a TimeSource into your class, use the real one in production and a TestTimeSource in tests, and move it forward with += instead of sleeping.

Summary

  • kotlin.time.Duration is a typed amount of time: 5.seconds, 1.5.hours; add, compare, convert with inWholeMinutes, split with toComponents, parse with Duration.parse.
  • measureTime and TimeSource.Monotonic measure elapsed time reliably; TestTimeSource gives deterministic tests. Never assert on exact timings.
  • Calendar work uses java.time: LocalDate, LocalDateTime, Instant, ZonedDateTime, Period. All are immutable; arithmetic returns new objects and clamps month ends.
  • Local types have no zone; convert to an Instant only by naming a ZoneId.
  • Format with DateTimeFormatter.ofPattern(..., Locale), store and exchange ISO text, and watch the letter case (MM vs mm, HH vs hh).
  • Pass a clock into code that needs the time so tests can control it.

Next: Random and Math