Dates and time
suggest changeKotlin's standard library has no calendar date types of its own on the JVM. Instead, Kotlin/JVM code uses the java.time package (JSR-310, Java 8+). It is immutable, thread-safe and well designed, and Kotlin makes it nicer with operators and ranges.
On top of that:
- the Kotlin standard library has
kotlin.time.DurationandTimeSourcefor measuring elapsed time, pluskotlin.time.InstantandClock(added in Kotlin 2.1.20) - the
kotlinx-datetimelibrary provides multiplatformLocalDate,LocalDateTimeandTimeZonefor code that must also run on Kotlin/JS or Kotlin/Native
This article covers:
- choosing the right type
- current date and time
- creating dates and doing date arithmetic
- comparing dates, ranges and iteration
- differences:
Duration,Period,ChronoUnit kotlin.time.Durationand measuring elapsed time- formatting and parsing
- time zones and daylight saving time
- Unix timestamps
- testable code with
Clock - legacy
java.util.Dateinterop - multiplatform
kotlinx-datetime
Which type to use
| Type | Example | Use for |
|---|---|---|
Instant |
2024-03-15T13:00:00Z |
a point on the timeline: timestamps, logs, database timestamptz |
LocalDate |
2024-03-15 |
a calendar date: birthday, due date |
LocalTime |
09:30 |
wall clock time: store opening hours |
LocalDateTime |
2024-03-15T09:30 |
date + time without a zone: "the meeting is at 9:30" before you know where |
ZonedDateTime |
2024-03-15T09:30-04:00[America/New_York] |
date + time in a real time zone, with DST rules |
OffsetDateTime |
2024-03-15T09:30-04:00 |
date + time with a fixed UTC offset, common in APIs and databases |
Duration |
PT8H25M |
an exact amount of time in seconds and nanoseconds |
Period |
P1Y2M3D |
an amount of calendar time in years, months, days |
A good default: store and transmit Instant (UTC), convert to ZonedDateTime only when showing a value to a user.
LocalDateTime is not a point in time. "2024-03-15T09:30" happens at different moments in Tokyo and New York. Don't use it for timestamps.
Current date and time
import java.time.*
fun main() {
println(Instant.now()) // always UTC
println(LocalDate.now()) // in the system default zone
println(LocalTime.now())
println(LocalDateTime.now())
println(ZonedDateTime.now())
println(ZonedDateTime.now(ZoneId.of("Asia/Tokyo")))
println(ZoneId.systemDefault())
}
Possible output:
2024-03-15T13:04:21.561874Z
2024-03-15
14:04:21.573061
2024-03-15T14:04:21.573225
2024-03-15T14:04:21.573513+01:00[Europe/Warsaw]
2024-03-15T22:04:21.574011+09:00[Asia/Tokyo]
Europe/Warsaw
Every now() without arguments depends on the machine's default time zone. On servers, either pass a zone explicitly or inject a Clock (see below).
Creating dates and times
import java.time.*
fun main() {
val date = LocalDate.of(2024, 3, 15)
val date2 = LocalDate.of(2024, Month.MARCH, 15)
val time = LocalTime.of(9, 30)
val dateTime = LocalDateTime.of(2024, 3, 15, 9, 30, 0)
val combined = date.atTime(time)
val startOfDay = date.atStartOfDay()
println(date)
println(date == date2)
println(time)
println(dateTime)
println(combined)
println(startOfDay)
println(date.year) // 2024
println(date.month) // MARCH
println(date.monthValue) // 3
println(date.dayOfMonth) // 15
println(date.dayOfWeek) // FRIDAY
println(date.dayOfYear) // 75
println(date.isLeapYear) // true
println(date.lengthOfMonth()) // 31
}
Output:
2024-03-15
true
09:30
2024-03-15T09:30
2024-03-15T09:30
2024-03-15T00:00
2024
MARCH
3
15
FRIDAY
75
true
31
Months are numbered 1 to 12, unlike the old java.util.Calendar where January was 0. Invalid values throw immediately:
import java.time.DateTimeException
import java.time.LocalDate
fun main() {
try {
LocalDate.of(2023, 2, 29)
} catch (e: DateTimeException) {
println(e.message)
}
}
Output:
Invalid date 'February 29' as '2023' is not a leap year
Date arithmetic
All types are immutable. Methods like plusDays() return a new value, so don't forget to use the result.
import java.time.*
fun main() {
val date = LocalDate.of(2024, 1, 31)
println(date.plusDays(10)) // 2024-02-10
println(date.plusWeeks(2)) // 2024-02-14
println(date.plusMonths(1)) // 2024-02-29 (clamped to last valid day)
println(date.minusYears(1)) // 2023-01-31
println(LocalDate.of(2024, 2, 29).plusYears(1)) // 2025-02-28
// with Period
println(date + Period.ofDays(1)) // 2024-02-01
println(date.plus(Period.of(1, 2, 3))) // 2025-04-03
// replace a single field
println(date.withDayOfMonth(1)) // 2024-01-01
println(date.withYear(2030)) // 2030-01-31
val time = LocalTime.of(23, 30)
println(time.plusHours(2)) // 01:30 (wraps around midnight)
}
Kotlin maps the + and - operators to plus() and minus(), so date + Period.ofDays(1) and instant - Duration.ofHours(1) work out of the box.
Month arithmetic is not reversible: 2024-01-31 + 1 month = 2024-02-29, but 2024-02-29 - 1 month = 2024-01-29.
Temporal adjusters
For "next Monday" or "last day of the month", use TemporalAdjusters:
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.temporal.TemporalAdjusters
fun main() {
val date = LocalDate.of(2024, 3, 15) // a Friday
println(date.with(TemporalAdjusters.next(DayOfWeek.MONDAY)))
println(date.with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY)))
println(date.with(TemporalAdjusters.previous(DayOfWeek.MONDAY)))
println(date.with(TemporalAdjusters.firstDayOfMonth()))
println(date.with(TemporalAdjusters.lastDayOfMonth()))
println(LocalDate.of(2024, 2, 1).with(TemporalAdjusters.lastDayOfMonth()))
println(date.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)))
println(date.with(TemporalAdjusters.firstDayOfNextYear()))
}
Output:
2024-03-18
2024-03-15
2024-03-11
2024-03-01
2024-03-31
2024-02-29
2024-03-04
2025-01-01
Comparing, ranges and iteration
All java.time value types implement Comparable, so Kotlin's comparison operators and ranges just work:
import java.time.LocalDate
fun main() {
val a = LocalDate.of(2024, 3, 15)
val b = LocalDate.of(2024, 4, 1)
println(a < b) // true
println(a.isBefore(b)) // true
println(a == LocalDate.of(2024, 3, 15)) // true
println(maxOf(a, b)) // 2024-04-01
val q1 = LocalDate.of(2024, 1, 1)..LocalDate.of(2024, 3, 31)
println(a in q1) // true
println(b in q1) // false
val dates = listOf(b, a, LocalDate.of(2023, 12, 24))
println(dates.sorted()) // [2023-12-24, 2024-03-15, 2024-04-01]
}
For ZonedDateTime and OffsetDateTime, == compares the zone too. Two values representing the same instant in different zones are not equal; use isEqual() or compare their toInstant().
A range of dates is a ClosedRange<LocalDate>, which supports in but can't be iterated. To loop over days, use datesUntil() (end exclusive) or generateSequence:
import java.time.LocalDate
fun main() {
val start = LocalDate.of(2024, 3, 1)
val end = LocalDate.of(2024, 3, 5)
start.datesUntil(end.plusDays(1)).forEach { d ->
println("$d ${d.dayOfWeek}")
}
val mondays = generateSequence(LocalDate.of(2024, 3, 4)) { it.plusWeeks(1) }
.takeWhile { it.monthValue == 3 }
.toList()
println(mondays)
}
Output:
2024-03-01 FRIDAY
2024-03-02 SATURDAY
2024-03-03 SUNDAY
2024-03-04 MONDAY
2024-03-05 TUESDAY
[2024-03-04, 2024-03-11, 2024-03-18, 2024-03-25]
Differences between dates
There are three tools, depending on what answer you want:
import java.time.*
import java.time.temporal.ChronoUnit
fun main() {
// total number of a single unit
val from = LocalDate.of(2024, 1, 15)
val to = LocalDate.of(2024, 12, 25)
println(ChronoUnit.DAYS.between(from, to)) // 345
println(ChronoUnit.WEEKS.between(from, to)) // 49
println(ChronoUnit.MONTHS.between(from, to)) // 11
println(from.until(to, ChronoUnit.DAYS)) // 345
// years, months and days, e.g. for age
val birthday = LocalDate.of(1990, 5, 17)
val age = Period.between(birthday, LocalDate.of(2024, 3, 15))
println(age) // P33Y9M27D
println("${age.years} years, ${age.months} months, ${age.days} days")
// exact elapsed time between times or instants
val d = Duration.between(LocalTime.of(9, 15), LocalTime.of(17, 40))
println(d) // PT8H25M
println(d.toMinutes()) // 505
println("${d.toHours()}h ${d.toMinutesPart()}m") // 8h 25m
}
Period counts calendar units, Duration counts exact seconds. Duration.between() on two LocalDate values throws UnsupportedTemporalTypeException because a date has no seconds; use ChronoUnit.DAYS.between() instead.
kotlin.time.Duration
kotlin.time.Duration is the idiomatic Kotlin type for amounts of time. It is used by coroutines (delay(2.seconds), withTimeout(5.seconds), see Cancellation and timeouts) and works on all platforms.
import kotlin.time.Duration
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
fun main() {
val timeout = 90.minutes
println(timeout) // 1h 30m
println(1.5.hours) // 1h 30m
println(2.days + 3.hours) // 2d 3h
println(1500.milliseconds) // 1.5s
println(timeout * 2) // 3h
println(timeout.inWholeSeconds) // 5400
println(timeout.toIsoString()) // PT1H30M
println(timeout > 1.hours) // true
timeout.toComponents { hours, minutes, seconds, _ ->
println("%02d:%02d:%02d".format(hours, minutes, seconds)) // 01:30:00
}
println(Duration.parse("1h 30m") == timeout) // true
println(Duration.parseIsoString("PT45S")) // 45s
}
Convert to and from java.time.Duration on the JVM with toJavaDuration() and toKotlinDuration():
import kotlin.time.Duration.Companion.seconds
import kotlin.time.toJavaDuration
import kotlin.time.toKotlinDuration
fun main() {
val k = 75.seconds
val j: java.time.Duration = k.toJavaDuration()
println(j) // PT1M15S
println(java.time.Duration.ofMinutes(3).toKotlinDuration()) // 3m
}
Measuring elapsed time
Never measure elapsed time with System.currentTimeMillis() or Instant.now(): the wall clock can jump when NTP adjusts it. Use the monotonic clock:
import kotlin.time.TimeSource
import kotlin.time.measureTime
import kotlin.time.measureTimedValue
fun slowSum(n: Int): Long {
var s = 0L
for (i in 1..n) s += i
return s
}
fun main() {
val elapsed = measureTime { slowSum(50_000_000) }
println("took $elapsed")
val (sum, t) = measureTimedValue { slowSum(10_000_000) }
println("sum=$sum in ${t.inWholeMilliseconds} ms")
val mark = TimeSource.Monotonic.markNow()
slowSum(1_000_000)
println("since mark: ${mark.elapsedNow()}")
}
Possible output:
took 21.3842ms
sum=50000005000000 in 4 ms
since mark: 412.6us
For serious benchmarks use JMH; see Performance.
Formatting and parsing
toString() produces ISO-8601, and parse() reads it back, which is what you want for JSON, logs and databases:
import java.time.*
fun main() {
val d = LocalDate.parse("2024-03-15")
val dt = LocalDateTime.parse("2024-03-15T09:30:00")
val i = Instant.parse("2024-03-15T13:00:00Z")
val z = ZonedDateTime.parse("2024-03-15T09:30-04:00[America/New_York]")
val o = OffsetDateTime.parse("2024-03-15T09:30:00+01:00")
println("$d $dt $i")
println(z)
println(o)
}
Output:
2024-03-15 2024-03-15T09:30 2024-03-15T13:00:00Z
2024-03-15T09:30-04:00[America/New_York]
2024-03-15T09:30+01:00
For custom formats, use DateTimeFormatter. Create formatters once and reuse them; they are immutable and thread-safe.
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.util.Locale
val dayFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy")
val longFormat: DateTimeFormatter =
DateTimeFormatter.ofPattern("EEEE, d MMMM yyyy 'at' HH:mm", Locale.US)
fun main() {
val dt = LocalDateTime.of(2024, 3, 15, 14, 30)
println(dt.format(dayFormat)) // 15.03.2024
println(dt.format(longFormat)) // Friday, 15 March 2024 at 14:30
println(dt.format(DateTimeFormatter.ofPattern("EEEE, d. MMMM yyyy", Locale.GERMAN)))
println(dt.format(DateTimeFormatter.ofPattern("h:mm a", Locale.US))) // 2:30 PM
println(dt.toLocalDate().format(
DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).withLocale(Locale.US)))
val parsed = LocalDate.parse("24.12.2024", dayFormat)
println(parsed) // 2024-12-24
}
Output:
15.03.2024
Friday, 15 March 2024 at 14:30
Freitag, 15. März 2024
2:30 PM
March 15, 2024
2024-12-24
The most common pattern letters:
| Letter | Meaning | Example |
|---|---|---|
yyyy |
year | 2024 |
MM / MMM / MMMM |
month | 03 / Mar / March |
dd / d |
day of month | 05 / 5 |
EEE / EEEE |
day of week | Fri / Friday |
HH |
hour 0-23 | 14 |
hh + a |
hour 1-12 + AM/PM | 02 PM |
mm / ss / SSS |
minute / second / millis | 30 / 05 / 123 |
VV / z / XXX |
zone id / zone name / offset | Europe/Warsaw / CET / +01:00 |
Two classic mistakes: mm is minutes and MM is months, and YYYY is the week-based year, not the calendar year:
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Locale
fun main() {
val d = LocalDate.of(2024, 12, 30)
println(d.format(DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.US))) // 2024-12-30
println(d.format(DateTimeFormatter.ofPattern("YYYY-MM-dd", Locale.US))) // 2025-12-30 !
}
Parsing invalid input throws DateTimeParseException. Wrap it to get a nullable result:
import java.time.LocalDate
import java.time.format.DateTimeParseException
fun parseDateOrNull(s: String): LocalDate? =
try {
LocalDate.parse(s)
} catch (e: DateTimeParseException) {
null
}
fun main() {
println(parseDateOrNull("2024-03-15")) // 2024-03-15
println(parseDateOrNull("2024-13-01")) // null
println(parseDateOrNull("15/03/2024")) // null
}
Time zones and daylight saving time
Use region-based zone ids like Europe/Warsaw or America/New_York, not abbreviations like EST or fixed offsets: only a region id knows the DST rules.
import java.time.*
fun main() {
val meeting = ZonedDateTime.of(
LocalDateTime.of(2024, 3, 15, 9, 0),
ZoneId.of("America/New_York"),
)
println(meeting)
println(meeting.withZoneSameInstant(ZoneId.of("Europe/Warsaw")))
println(meeting.withZoneSameInstant(ZoneId.of("Asia/Tokyo")))
println(meeting.toInstant())
println(meeting.toOffsetDateTime())
// withZoneSameLocal keeps the wall clock time and changes the instant
println(meeting.withZoneSameLocal(ZoneId.of("Europe/Warsaw")))
}
Output:
2024-03-15T09:00-04:00[America/New_York]
2024-03-15T14:00+01:00[Europe/Warsaw]
2024-03-15T22:00+09:00[Asia/Tokyo]
2024-03-15T13:00:00Z
2024-03-15T09:00-04:00
2024-03-15T09:00+01:00[Europe/Warsaw]
In the US, DST started on 2024-03-10, while in Europe it started on 2024-03-31, so for these two weeks New York is 5 hours behind Warsaw instead of the usual 6.
DST gaps and overlaps
When clocks jump forward, some local times don't exist. When they fall back, some local times happen twice. java.time resolves both cases predictably:
import java.time.*
fun main() {
val ny = ZoneId.of("America/New_York")
// 2024-03-10: clocks jump from 02:00 to 03:00
val gap = LocalDateTime.of(2024, 3, 10, 2, 30).atZone(ny)
println(gap) // shifted forward by the length of the gap
// 2024-11-03: clocks go back from 02:00 to 01:00, 01:30 happens twice
val overlap = LocalDateTime.of(2024, 11, 3, 1, 30).atZone(ny)
println(overlap) // earlier offset by default
println(overlap.withLaterOffsetAtOverlap())
// "one day later" vs "24 hours later" across the DST change
val before = ZonedDateTime.of(2024, 3, 9, 12, 0, 0, 0, ny)
println(before.plusDays(1))
println(before.plusHours(24))
println(Duration.between(before, before.plusDays(1)))
}
Output:
2024-03-10T03:30-04:00[America/New_York]
2024-11-03T01:30-04:00[America/New_York]
2024-11-03T01:30-05:00[America/New_York]
2024-03-10T12:00-04:00[America/New_York]
2024-03-10T13:00-04:00[America/New_York]
PT23H
plusDays(1) keeps the wall clock time, plusHours(24) adds exact time. For "remind me at the same time tomorrow" you want the former; for "token expires in 24 hours" the latter (and with an Instant there is no ambiguity at all).
Unix timestamps
import java.time.*
fun main() {
val i = Instant.ofEpochSecond(1_700_000_000)
println(i) // 2023-11-14T22:13:20Z
println(i.epochSecond) // 1700000000
println(i.toEpochMilli()) // 1700000000000
val fromMillis = Instant.ofEpochMilli(1_700_000_000_000)
val local = fromMillis.atZone(ZoneId.of("Europe/Warsaw")).toLocalDateTime()
println(local) // 2023-11-14T23:13:20
// LocalDateTime -> epoch seconds requires a zone or offset
val ldt = LocalDateTime.of(2024, 1, 1, 0, 0)
println(ldt.toEpochSecond(ZoneOffset.UTC)) // 1704067200
println(ldt.atZone(ZoneId.of("Asia/Tokyo")).toEpochSecond()) // 1704034800
}
Watch the unit: JavaScript and Java use milliseconds, most Unix tools and many APIs use seconds. A "date in 1970" or "year 55000" is a sign of mixing them up.
Testable code with Clock
Code that calls LocalDate.now() directly is hard to test. Every now() has an overload taking a java.time.Clock, so inject one:
import java.time.*
import java.time.temporal.ChronoUnit
class Subscription(val expiresOn: LocalDate, private val clock: Clock = Clock.systemUTC()) {
fun isActive(): Boolean = !LocalDate.now(clock).isAfter(expiresOn)
fun daysLeft(): Long = ChronoUnit.DAYS.between(LocalDate.now(clock), expiresOn)
}
fun main() {
val fixed = Clock.fixed(Instant.parse("2024-03-15T10:00:00Z"), ZoneOffset.UTC)
val sub = Subscription(LocalDate.of(2024, 3, 20), fixed)
println(sub.isActive()) // true
println(sub.daysLeft()) // 5
val later = Clock.offset(fixed, Duration.ofDays(6))
println(Subscription(LocalDate.of(2024, 3, 20), later).isActive()) // false
}
For coroutine code, kotlinx-coroutines-test provides virtual time through runTest; kotlin.time.TestTimeSource lets you advance a fake monotonic clock manually.
Legacy java.util.Date and Calendar
Old APIs (JDBC drivers, some Java libraries) still use java.util.Date, Calendar and java.sql.Timestamp. Convert at the boundary and use java.time everywhere else:
import java.time.*
import java.util.Date
fun main() {
val legacy = Date(1_700_000_000_000)
val instant: Instant = legacy.toInstant()
println(instant) // 2023-11-14T22:13:20Z
val back: Date = Date.from(Instant.parse("2024-03-15T13:00:00Z"))
println(back.time) // 1710507600000
val ts = java.sql.Timestamp.valueOf(LocalDateTime.of(2024, 3, 15, 9, 30))
println(ts.toLocalDateTime()) // 2024-03-15T09:30
}
Modern JDBC drivers accept LocalDate, LocalDateTime and OffsetDateTime directly through setObject() / getObject(i, LocalDate::class.java); see JDBC from Kotlin. Avoid SimpleDateFormat: it is mutable and not thread-safe.
Multiplatform: kotlinx-datetime
java.time exists only on the JVM (and Android API 26+, or older with desugaring). For Kotlin Multiplatform, use kotlinx-datetime:
// build.gradle.kts
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.8.0")
}
Since version 0.7, Instant and Clock come from the standard library's kotlin.time package; kotlinx-datetime adds calendar types and time zones on top. These standard library types were experimental until Kotlin 2.3; with an older compiler, add @OptIn(ExperimentalTime::class):
import kotlinx.datetime.*
import kotlin.time.Clock
import kotlin.time.Instant
fun main() {
val now: Instant = Clock.System.now()
val tz = TimeZone.of("Europe/Warsaw")
println(now.toLocalDateTime(tz))
val date = LocalDate(2024, 1, 31)
println(date.plus(1, DateTimeUnit.MONTH)) // 2024-02-29
println(date.plus(DatePeriod(months = 1, days = 3))) // 2024-03-03
println(date.daysUntil(LocalDate(2024, 12, 25))) // 329
println(LocalDate.parse("2024-03-15").dayOfWeek) // FRIDAY
val meeting = LocalDateTime(2024, 3, 15, 9, 0).toInstant(TimeZone.of("America/New_York"))
println(meeting) // 2024-03-15T13:00:00Z
}
On the JVM, kotlinx-datetime types convert to java.time with toJavaLocalDate(), toKotlinLocalDate() and similar functions.
Common mistakes
- Using
LocalDateTimefor timestamps. It has no zone, so it is ambiguous. UseInstantorOffsetDateTime. - Depending on the default time zone.
LocalDate.now()on a server in UTC and a laptop in Tokyo return different dates. Pass aZoneIdorClock. - Ignoring the return value.
date.plusDays(1)does not modifydate. YYYYandmmin patterns when you meantyyyyandMM.- Measuring durations with the wall clock. Use
measureTimeorTimeSource.Monotonic. - Assuming a day is 24 hours. Across DST changes, a day is 23 or 25 hours long.
- Using fixed offsets for future events.
-05:00is New York only in winter; store theZoneId.
Summary
| Task | Code |
|---|---|
| current timestamp | Instant.now() |
| today in a zone | LocalDate.now(ZoneId.of("Europe/Warsaw")) |
| create a date | LocalDate.of(2024, 3, 15) |
| add time | date.plusDays(7), date + Period.ofMonths(1) |
| last day of month | date.with(TemporalAdjusters.lastDayOfMonth()) |
| days between | ChronoUnit.DAYS.between(a, b) |
| age | Period.between(birthday, today).years |
| format | dt.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")) |
| parse | LocalDate.parse("2024-03-15") |
| convert zone | zdt.withZoneSameInstant(ZoneId.of("Asia/Tokyo")) |
| from epoch seconds | Instant.ofEpochSecond(s) |
| Kotlin duration | 90.minutes, 2.seconds |
| measure elapsed time | measureTime { ... } |
| testable now | LocalDate.now(clock) with Clock.fixed(...) |