### Gradle Installation for Kotlin Multiplatform Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Add the kotlinx-datetime dependency to your commonMain source set in Gradle for multiplatform projects. ```kotlin repositories { mavenCentral() } kotlin { sourceSets { commonMain { dependencies { implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.8.0") } } } } ``` -------------------------------- ### JS/Wasm Time Zone Support Setup Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt For Kotlin/JS and Wasm, install the '@js-joda/timezone' npm package and initialize it for full time zone support. ```kotlin // Kotlin/JS kotlin { sourceSets { val jsMain by getting { dependencies { implementation(npm("@js-joda/timezone", "2.18.1")) } } } } // Initialization code in any JS source file: @JsModule("@js-joda/timezone") @JsNonModule external object JsJodaTimeZoneModule @OptIn(ExperimentalJsExport::class) @JsExport val jsJodaTz = JsJodaTimeZoneModule ``` -------------------------------- ### Checkout Master Branch Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md Use this command to switch to the master branch before starting the release process. ```bash git checkout master ``` -------------------------------- ### Get Current Instant and Today's Date Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Use `Clock.System.now()` to get the current physical time as an `Instant`. `Clock.System.todayIn(timeZone)` provides today's date in a specified `TimeZone`. ```kotlin import kotlinx.datetime.* import kotlin.time.Clock // Current instant (physical time) val now: kotlin.time.Instant = Clock.System.now() println(now) // e.g. 2025-06-04T12:34:56.789Z // Today's date in a specific time zone val todayUtc: LocalDate = Clock.System.todayIn(TimeZone.UTC) val todayBerlin: LocalDate = Clock.System.todayIn(TimeZone.of("Europe/Berlin")) println(todayUtc) // e.g. 2025-06-04 println(todayBerlin) // could be 2025-06-05 if it's already past midnight in Berlin ``` -------------------------------- ### Get LocalDate from Instant Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Obtains the current local date from an Instant using the system's default time zone. Requires Clock.System and TimeZone. ```kotlin val now: Instant = Clock.System.now() val today: LocalDate = now.toLocalDateTime(TimeZone.currentSystemDefault()).date // or shorter val today: LocalDate = Clock.System.todayIn(TimeZone.currentSystemDefault()) ``` -------------------------------- ### Get LocalTime from Instant Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Extracts the LocalTime component from an Instant by first converting it to LocalDateTime using the system's default time zone. ```kotlin val now: Instant = Clock.System.now() val thisTime: LocalTime = now.toLocalDateTime(TimeZone.currentSystemDefault()).time ``` -------------------------------- ### Calculate Calendar Difference Between Instants Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Use `Instant.periodUntil` to get the calendar difference between two instants in a specified time zone. ```kotlin val period: DateTimePeriod = instantInThePast.periodUntil(Clock.System.now(), TimeZone.UTC) ``` -------------------------------- ### Work with TimeZone Rules Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Demonstrates TimeZone construction using UTC, system defaults, IANA identifiers, and fixed offsets. Shows how to list available zone IDs and convert between `Instant` and `LocalDateTime` using a specified `TimeZone`. ```kotlin import kotlinx.datetime.* import kotlin.time.Clock // Constants and construction val utc = TimeZone.UTC // fixed UTC val system = TimeZone.currentSystemDefault() // system time zone (re-read each call) val berlin = TimeZone.of("Europe/Berlin") val fixed = TimeZone.of("UTC+05:30") // India IST as a fixed offset // List all available identifiers println(TimeZone.availableZoneIds.take(5)) // [Africa/Abidjan, Africa/Accra, ...] // Convert Instant → LocalDateTime val now = Clock.System.now() val localBerlin: LocalDateTime = now.toLocalDateTime(berlin) // Convert LocalDateTime → Instant val scheduled = LocalDateTime(2025, 11, 2, 2, 30) // ambiguous in US fall-back zones val instant: kotlin.time.Instant = scheduled.toInstant(TimeZone.of("America/New_York")) // Get current UTC offset at a specific instant val offset: UtcOffset = berlin.offsetAt(now) println(offset) // e.g. +02:00 // FixedOffsetTimeZone val offsetTz = FixedOffsetTimeZone(UtcOffset(hours = 5, minutes = 30)) println(offsetTz.offset.totalSeconds) // 19800 ``` -------------------------------- ### Running kotlinx-datetime Benchmarks Source: https://github.com/kotlin/kotlinx-datetime/blob/master/benchmarks/README.md Commands to build the JMH benchmark JAR and execute performance tests. Users can run all benchmarks or target specific classes and methods with custom JVM parameters for iterations and timing. ```bash ./gradlew :benchmarks:jmhJar java -jar benchmarks.jar java -jar benchmarks.jar Formatting java -jar benchmarks.jar FormattingBenchmark.formatIso java -jar benchmarks.jar -wi 5 -i 5 -tu us -bm thrpt Formatting java -jar benchmarks.jar -help ``` -------------------------------- ### Create Compatibility Tag Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md Create a Git tag for the compatibility release. ```git git tag v-0.6.x-compat version--compat git push --tags ``` -------------------------------- ### Get YearMonth from LocalDate Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Extracts the YearMonth component from a LocalDate instance. ```kotlin val day = LocalDate(2020, 2, 21) val yearMonth: YearMonth = day.yearMonth ``` -------------------------------- ### Convert LocalDateTime to Instant and Perform Arithmetic Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Demonstrates converting `LocalDateTime` to `Instant` to perform arithmetic safely, avoiding issues with daylight saving time transitions, and then converting back to `LocalDateTime`. ```kotlin val timeZone = TimeZone.of("Europe/Berlin") val localDateTime = LocalDateTime.parse("2021-03-27T02:16:20") val instant = localDateTime.toInstant(timeZone) val instantOneDayLater = instant.plus(1, DateTimeUnit.DAY, timeZone) val localDateTimeOneDayLater = instantOneDayLater.toLocalDateTime(timeZone) // 2021-03-28T03:16:20, as 02:16:20 that day is in a time gap val instantTwoDaysLater = instant.plus(2, DateTimeUnit.DAY, timeZone) val localDateTimeTwoDaysLater = instantTwoDaysLater.toLocalDateTime(timeZone) // 2021-03-29T02:16:20 ``` -------------------------------- ### Deploy Normal Artifact Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md Initiate the deployment of the normal artifact in TeamCity. ```text Version: Artifacts to publish: all ``` -------------------------------- ### Construct and Use UtcOffset Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Shows how to construct `UtcOffset` objects for fixed offsets from UTC, including positive, negative, and zero offsets. Demonstrates accessing the total seconds and formatting the offset. `orNull` provides safe construction for potentially invalid minute values. ```kotlin import kotlinx.datetime.* // Construction val plus5h30m = UtcOffset(hours = 5, minutes = 30) val minus3 = UtcOffset(hours = -3) val zero = UtcOffset.ZERO println(plus5h30m.totalSeconds) // 19800 println(plus5h30m) // +05:30 println(zero) // Z // Null-safe val safe: UtcOffset? = UtcOffset.orNull(hours = 3, minutes = 61) // null — minutes > 59 // Parse / format val parsed = UtcOffset.parse("+05:30") val basic = UtcOffset.parse("+0530", UtcOffset.Formats.FOUR_DIGITS) println(UtcOffset(hours = 2).format(UtcOffset.Formats.FOUR_DIGITS)) // "+0200" // Convert to FixedOffsetTimeZone val tz: FixedOffsetTimeZone = plus5h30m.asTimeZone() ``` -------------------------------- ### Create Release Branch Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md Create a new branch specifically for the release. Replace `` with the actual release version. ```bash git checkout -b version- ``` -------------------------------- ### Using DateTimeUnit for Time Calculations in Kotlin Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Demonstrates predefined time units and how to create custom units by multiplication. Useful for date and time arithmetic. ```kotlin import kotlinx.datetime.* // Predefined units println(DateTimeUnit.NANOSECOND) println(DateTimeUnit.MICROSECOND) println(DateTimeUnit.MILLISECOND) println(DateTimeUnit.SECOND) println(DateTimeUnit.MINUTE) println(DateTimeUnit.HOUR) println(DateTimeUnit.DAY) println(DateTimeUnit.WEEK) println(DateTimeUnit.MONTH) println(DateTimeUnit.QUARTER) println(DateTimeUnit.YEAR) // Custom units via multiplication val tenSeconds = DateTimeUnit.SECOND * 10 val twoWeeks = DateTimeUnit.WEEK * 2 val halfYear = DateTimeUnit.MONTH * 6 // Use with LocalDate val date = LocalDate(2025, 1, 1) println(date.plus(1, twoWeeks)) println(date.until(LocalDate(2025, 7, 1), halfYear)) // Use with Instant val tz = TimeZone.UTC val now = kotlin.time.Clock.System.now() println(now.plus(1, DateTimeUnit.QUARTER, tz)) ``` -------------------------------- ### Deploy Compatibility Artifact Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md Initiate the deployment of the compatibility artifact in TeamCity. ```text Version: -0.6.x-compat Artifacts to publish: core only ``` -------------------------------- ### Create GitHub Release Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md Create a GitHub release tag and description based on the normal release branch. ```git git tag v version--normal ``` -------------------------------- ### DateTimePeriod and DatePeriod Construction and Parsing Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Understand how to construct, parse, and use DateTimePeriod and DatePeriod objects. These represent durations decomposed into calendar units. Demonstrates ISO 8601 parsing and conversion from Duration. ```kotlin import kotlinx.datetime.* import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.minutes // Construction — values are normalised val p1 = DateTimePeriod(years = 1, months = 14, days = 3, hours = 25, minutes = 90) println(p1) // P2Y2M3DT2H30M (normalized: 14→1y2m, 25h90m→2h30m) val datePeriod = DatePeriod(years = 2, months = 3, days = 10) println(datePeriod) // P2Y3M10D // Parse ISO 8601 duration strings val period: DateTimePeriod = DateTimePeriod.parse("P1Y6M15DT3H30M") println(period.years) // 1 println(period.months) // 6 println(period.days) // 15 println(period.hours) // 3 println(period.minutes) // 30 // Null-safe parse val maybe: DateTimePeriod? = DateTimePeriod.parseOrNull("not-a-period") // null // Use with Instant val tz = TimeZone.UTC val now = kotlin.time.Clock.System.now() val later = now.plus(DateTimePeriod(months = 6, days = 15), tz) val earlier = later.minus(DatePeriod(years = 1), tz) // Convert Duration to DateTimePeriod (only time components; no calendar date components) val dp: DateTimePeriod = (3.hours + 15.minutes).toDateTimePeriod() println(dp) // PT3H15M ``` -------------------------------- ### Convert Instant and Local Datetime to/from ISO 8601 String Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Use toString() to convert to ISO 8601 string format and parse() to convert back. LocalDate and LocalTime have specific ISO 8601 formats. ```kotlin val localDateTime = LocalDateTime(2025, 3, 21, 12, 27, 35, 124365453) localDateTime.toString() // 2025-03-21T12:27:35.124365453 val sameLocalDateTime = LocalDateTime.parse("2025-03-21T12:27:35.124365453") ``` ```kotlin LocalDate.parse("2010-06-01") ``` ```kotlin LocalTime.parse("12:01:03") ``` ```kotlin LocalTime.parse("12:00:03.999") ``` ```kotlin LocalTime.parse("12:0:03.999") // fails with an IllegalArgumentException ``` -------------------------------- ### Create Compatibility Branch Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md Create a new branch for the compatibility artifact release. ```git git checkout -b version--compat version- ``` -------------------------------- ### Convert Stdlib Instant to kotlinx-datetime Instant Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Use this extension function to convert a `kotlin.time.Instant` to a `kotlinx.datetime.Instant`. This is useful when a third-party library requires the `kotlinx-datetime` version. ```kotlin kotlin.time.Instant.toDeprecatedInstant(): kotlinx.datetime.Instant ``` -------------------------------- ### Download and Compile Timezone Database Source: https://github.com/kotlin/kotlinx-datetime/blob/master/UPDATE_TIMEZONE_DATABASE.md This Gradle task downloads and compiles the IANA timezone database for Wasm/WASI. Ensure you have updated the version in gradle.properties and README.md first. ```bash ./gradlew tzdbDownloadAndCompile ``` -------------------------------- ### Convert kotlinx-datetime Instant to Stdlib Instant Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Use this extension function to convert an `kotlinx.datetime.Instant` to a `kotlin.time.Instant` when migrating or interacting with libraries that expect the standard library's type. ```kotlin kotlinx.datetime.Instant.toStdlibInstant(): kotlin.time.Instant ``` -------------------------------- ### Converting Unicode Patterns to Kotlin DSL in Kotlin Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Demonstrates converting a Unicode date/time pattern string into the equivalent Kotlin DSL format builder. Useful for migrating existing formatting logic. ```kotlin import kotlinx.datetime.* import kotlinx.datetime.format.* // --- Convert a Unicode pattern to the Kotlin DSL (useful for migration) --- println(DateTimeFormat.formatAsKotlinBuilderDsl(DateTimeComponents.Format { byUnicodePattern("yyyy-MM-dd'T'HH:mm:ss") })) ``` -------------------------------- ### Commit and Push Compatibility Changes Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md Commit the changes to gradle.properties and push the compatibility branch. ```git git commit -a -m 'Version , compatibility artifact' ``` ```git git push -u origin version--compat ``` -------------------------------- ### Instant Arithmetic with TimeZone Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Perform time-based and calendar-based arithmetic on Instant objects. Calendar-based operations require a TimeZone. Demonstrates adding/subtracting durations, measuring periods, formatting, and parsing Instants. ```kotlin import kotlinx.datetime.* import kotlin.time.Clock import kotlin.time.Instant import kotlin.time.Duration.Companion.hours val tz = TimeZone.of("America/New_York") val now: Instant = Clock.System.now() // Time-based arithmetic (no TZ needed) val inOneHour = now + 2.hours val anHourAgo = now - 1.hours // Calendar-based arithmetic (TZ required) val tomorrow = now.plus(1, DateTimeUnit.DAY, tz) val nextMonth = now.plus(1, DateTimeUnit.MONTH, tz) val threeYearsLater = now.plus(DateTimePeriod(years = 3, months = 1), tz) // Measuring calendar differences val past: Instant = Instant.parse("2020-01-01T00:00:00Z") val period: DateTimePeriod = past.periodUntil(now, TimeZone.UTC) println("${period.years} years, ${period.months} months, ${period.days} days") val diffMonths: Long = past.until(now, DateTimeUnit.MONTH, TimeZone.UTC) val diffDays: Int = past.daysUntil(now, TimeZone.UTC) val diffYears: Int = past.yearsUntil(now, TimeZone.UTC) println("$diffMonths months | $diffDays days | $diffYears years") // Format an Instant with an explicit offset val formatted = now.format(DateTimeComponents.Formats.ISO_DATE_TIME_OFFSET, UtcOffset(hours = 2)) println(formatted) // e.g. 2025-06-04T14:34:56.789+02:00 // Parse an Instant from ISO string val parsed: Instant = Instant.parse("2025-01-07T23:16:15.53+02:00", DateTimeComponents.Formats.ISO_DATE_TIME_OFFSET) ``` -------------------------------- ### Construct LocalTime from Components Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Creates a LocalTime instance from hour, minute, second, and nanosecond components. Hour and minute are mandatory. ```kotlin val knownTime = LocalTime(hour = 23, minute = 59, second = 12) val timeWithNanos = LocalTime(hour = 23, minute = 59, second = 12, nanosecond = 999) val hourMinute = LocalTime(hour = 12, minute = 13) ``` -------------------------------- ### Compare Release Branches Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md Compare the compatibility branch with the normal branch to verify code differences. ```git git diff version--compat version--normal ``` -------------------------------- ### Formatting with DateTimeComponents Builder for RFC 1123 in Kotlin Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Shows how to format a date and time according to the RFC 1123 standard using the DateTimeComponents builder. Useful for HTTP headers and other network protocols. ```kotlin import kotlinx.datetime.* import kotlinx.datetime.format.* // Format with DateTimeComponents builder (e.g. RFC 1123) val rfc1123 = DateTimeComponents.Formats.RFC_1123.format { setDate(LocalDate(2025, 6, 1)) hour = 14; minute = 30; second = 0 setOffset(UtcOffset(hours = 2)) } println(rfc1123) ``` -------------------------------- ### Update Website Version List Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md Update the version list in the kotlin-web-site repository. ```kotlin dateTimeVersion = "" ``` -------------------------------- ### Convert Instant to LocalDateTime in UTC and System Default TimeZone Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Converts an Instant to LocalDateTime in UTC and the system's default time zone. Requires Clock.System and TimeZone. ```kotlin val currentMoment: Instant = Clock.System.now() val datetimeInUtc: LocalDateTime = currentMoment.toLocalDateTime(TimeZone.UTC) val datetimeInSystemZone: LocalDateTime = currentMoment.toLocalDateTime(TimeZone.currentSystemDefault()) ``` -------------------------------- ### Parsing and Converting ISO Offset Datetime with DateTimeComponents in Kotlin Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Demonstrates parsing a full ISO offset datetime string and converting it to LocalDateTime, UtcOffset, and Instant. Useful for handling standard datetime formats. ```kotlin import kotlinx.datetime.* import kotlinx.datetime.format.* // Parse a full ISO offset datetime val isoOffset = DateTimeComponents.Formats.ISO_DATE_TIME_OFFSET.parse("2025-06-01T14:30:00+02:00") println(isoOffset.toLocalDateTime()) println(isoOffset.toUtcOffset()) val instant = isoOffset.toInstantUsingOffset() println(instant) ``` -------------------------------- ### Commit and Push Changes Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md Commit the version changes and push the new release branch to the remote repository. Replace `` with the actual release version. ```bash git commit -a -m 'Version ' git push -u origin version- ``` -------------------------------- ### Create Normal Release Branch Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md Create a new branch for the normal release. ```git git checkout -b version--normal version- ``` -------------------------------- ### Custom LocalDate Formatting and Parsing in Kotlin Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Shows how to define custom date formats for parsing and formatting LocalDate objects using a DSL. Useful for handling specific regional date formats. ```kotlin import kotlinx.datetime.* import kotlinx.datetime.format.* // --- LocalDate custom format --- val usDate = LocalDate.Format { monthNumber(padding = Padding.ZERO) char('/') day(padding = Padding.ZERO) char('/') year() } println(usDate.format(LocalDate(2025, 6, 1))) println(usDate.parse("12/25/2025")) ``` -------------------------------- ### Download Windows Timezone Mappings Source: https://github.com/kotlin/kotlinx-datetime/blob/master/UPDATE_TIMEZONE_DATABASE.md This Gradle task downloads the latest mapping between Windows and IANA timezone names. If it fails, new mappings may have been written to the filesystem, requiring a `git diff` to verify. ```bash ./gradlew downloadWindowsZonesMapping ``` -------------------------------- ### Convert between kotlinx-datetime and java.time types on JVM Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Provides extension functions for seamless conversion between kotlinx-datetime types and their java.time counterparts on the JVM. These conversions are zero-overhead. ```kotlin import kotlinx.datetime.* import kotlinx.datetime.toJavaLocalDate import kotlinx.datetime.toKotlinLocalDate import kotlinx.datetime.toJavaZoneId import kotlinx.datetime.toKotlinTimeZone import java.time.LocalDate as JLocalDate import java.time.ZoneId // LocalDate ↔ java.time.LocalDate val kDate: LocalDate = LocalDate(2025, 6, 1) val jDate: JLocalDate = kDate.toJavaLocalDate() val kDate2: LocalDate = jDate.toKotlinLocalDate() println(kDate == kDate2) // true // Instant ↔ java.time.Instant (via stdlib) val kInstant: kotlin.time.Instant = kotlin.time.Instant.parse("2025-06-01T00:00:00Z") val jInstant: java.time.Instant = kInstant.toJavaInstant() val kInstant2 = jInstant.toKotlinInstant() // TimeZone ↔ java.time.ZoneId val kTz: TimeZone = TimeZone.of("America/New_York") val jZone: ZoneId = kTz.toJavaZoneId() val kTz2: TimeZone = jZone.toKotlinTimeZone() println(kTz == kTz2) // true ``` -------------------------------- ### View Git Log Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md This command helps in reviewing commit messages since the last release to aid in writing release notes. ```bash git log origin/latest-release.. ``` -------------------------------- ### Construct LocalDateTime from Components Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Creates a LocalDateTime instance from individual year, month, day, hour, minute, second, and nanosecond components. ```kotlin val kotlinReleaseDateTime = LocalDateTime(2016, 2, 15, 16, 57, 0, 0) ``` -------------------------------- ### Formatting Instant with UTC Offset in Kotlin Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Uses the predefined ISO_DATE_TIME_OFFSET format to format an Instant. This is a standard way to represent points in time with timezone information. ```kotlin import kotlinx.datetime.* import kotlinx.datetime.format.* // --- Instant with UTC offset --- val rfc3339 = DateTimeComponents.Formats.ISO_DATE_TIME_OFFSET val now = kotlin.time.Clock.System.now() println(now.format(rfc3339)) ``` -------------------------------- ### Add kotlinx-datetime Dependency for Single-Platform Projects Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Add the kotlinx-datetime library to the dependencies block for single-platform Kotlin projects. Specify the desired version. ```groovy dependencies { implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.8.0") } ``` -------------------------------- ### Add kotlinx-datetime Dependency for Multiplatform Projects Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Include the kotlinx-datetime library in the commonMain source set for multiplatform Kotlin projects. Replace '0.8.0' with the desired version. ```kotlin kotlin { sourceSets { commonMain { dependencies { implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.8.0") } } } } ``` -------------------------------- ### TimeZone Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Provides the rules for converting between `Instant` and `LocalDateTime`. Use IANA identifiers such as `"Europe/Berlin"` or fixed offsets like `"UTC+3"`. It allows obtaining time zones by ID, the system default, or fixed offsets, and converting between instants and local date-times. ```APIDOC ## `TimeZone` — Time zone rules Provides the rules for converting between `Instant` and `LocalDateTime`. Use IANA identifiers such as `"Europe/Berlin"` or fixed offsets like `"UTC+3"`. ```kotlin import kotlinx.datetime.* import kotlin.time.Clock // Constants and construction val utc = TimeZone.UTC // fixed UTC val system = TimeZone.currentSystemDefault() // system time zone (re-read each call) val berlin = TimeZone.of("Europe/Berlin") val fixed = TimeZone.of("UTC+05:30") // India IST as a fixed offset // List all available identifiers println(TimeZone.availableZoneIds.take(5)) // [Africa/Abidjan, Africa/Accra, ...] // Convert Instant → LocalDateTime val now = Clock.System.now() val localBerlin: LocalDateTime = now.toLocalDateTime(berlin) // Convert LocalDateTime → Instant val scheduled = LocalDateTime(2025, 11, 2, 2, 30) // ambiguous in US fall-back zones val instant: kotlin.time.Instant = scheduled.toInstant(TimeZone.of("America/New_York")) // Get current UTC offset at a specific instant val offset: UtcOffset = berlin.offsetAt(now) println(offset) // e.g. +02:00 // FixedOffsetTimeZone val offsetTz = FixedOffsetTimeZone(UtcOffset(hours = 5, minutes = 30)) println(offsetTz.offset.totalSeconds) // 19800 ``` ``` -------------------------------- ### Initialize JS Time Zone for Wasm/JS Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Add this initialization code after adding the JS time zone dependency for Wasm/JS projects. ```kotlin @JsModule("@js-joda/timezone") external object JsJodaTimeZoneModule private val jsJodaTz = JsJodaTimeZoneModule ``` -------------------------------- ### Add Maven Central Repository Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Ensure the Maven Central repository is available for dependency resolution. This is a prerequisite for fetching libraries. ```kotlin repositories { mavenCentral() } ``` -------------------------------- ### Convert Stdlib Clock to kotlinx-datetime Clock Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Use this extension function to convert a `kotlin.time.Clock` to a `kotlinx.datetime.Clock`. This is useful when a third-party library requires the `kotlinx-datetime` version. ```kotlin kotlin.time.Clock.toStdlibClock(): kotlin.time.Clock ``` -------------------------------- ### Construct LocalDate from Components Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Creates a LocalDate instance from individual year, month, and day components. ```kotlin val knownDate = LocalDate(2020, 2, 21) ``` -------------------------------- ### Update Version in kotlin-web-site Repository Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md Update the `dateTimeVersion` in the `v.list` file within the JetBrains/kotlin-web-site repository. ```plaintext Update `dateTimeVersion` to `` in . ``` -------------------------------- ### Define Custom Date Format Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Create a custom LocalDate format using a builder DSL. The formatted date can then be parsed or printed using other formats like ISO_BASIC. ```kotlin // import kotlinx.datetime.format.* val dateFormat = LocalDate.Format { monthNumber(padding = Padding.SPACE) char('/') day() char(' ') year() } val date = dateFormat.parse("12/24 2023") println(date.format(LocalDate.Formats.ISO_BASIC)) // "20231224" ``` -------------------------------- ### Construct and Use YearMonth Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Constructs YearMonth objects and accesses their properties. Use `orNull` for safe construction when month values might be invalid. The `numberOfDays`, `firstDay`, `lastDay`, and `days` properties provide information about the month's duration. ```kotlin import kotlinx.datetime.* // Construction val ym = YearMonth(2025, 6) val safe: YearMonth? = YearMonth.orNull(2025, 13) // null // Properties println(ym.year) // 2025 println(ym.month) // JUNE println(ym.numberOfDays)// 30 println(ym.firstDay) // 2025-06-01 println(ym.lastDay) // 2025-06-30 println(ym.days) // LocalDateRange: 2025-06-01..2025-06-30 // Get a specific day in the month val payday: LocalDate = ym.onDay(25) // 2025-06-25 // Derive from LocalDate val card = LocalDate(2025, 6, 1) println(card.yearMonth) // 2025-06 // Arithmetic val nextMonth = ym.plusMonth() // 2025-07 val nextYear = ym.plusYear() // 2026-06 val offset = ym.plus(18, DateTimeUnit.MONTH) // 2026-12 println(ym.monthsUntil(YearMonth(2026, 6))) // 12 println(ym.yearsUntil(YearMonth(2027, 6))) // 2 // Range for (month in ym..YearMonth(2025, 12)) { println(month) // 2025-06, 2025-07, ..., 2025-12 } // Parse / format val parsed = YearMonth.parse("2025-06") println(ym.toString()) // "2025-06" ``` -------------------------------- ### Add DateTime Units or Period to Instant Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Add a specific amount of `DateTimeUnit` or a `DateTimePeriod` to an `Instant` using the `plus` function, requiring a `TimeZone` for accurate calculation. ```kotlin val now = Clock.System.now() val systemTZ = TimeZone.currentSystemDefault() val tomorrow = now.plus(2, DateTimeUnit.DAY, systemTZ) val threeYearsAndAMonthLater = now.plus(DateTimePeriod(years = 3, months = 1), systemTZ) ``` -------------------------------- ### Convert kotlinx-datetime Clock to Stdlib Clock Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Use this extension function to convert an `kotlinx.datetime.Clock` to a `kotlin.time.Clock` when migrating or interacting with libraries that expect the standard library's type. ```kotlin kotlinx.datetime.Clock.toDeprecatedClock(): kotlinx.datetime.Clock ``` -------------------------------- ### Update kotlinx-datetime Version in compiler-server Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md Update the `kotlinx-datetime` version in the `libs.versions.toml` file within the JetBrains/kotlin-compiler-server repository. ```plaintext Update `kotlinx-datetime` to `` in ``` -------------------------------- ### Parsing Partial Date Formats with DateTimeComponents in Kotlin Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Shows how to parse a string containing only month and day using DateTimeComponents. Useful when the year is not provided or irrelevant. ```kotlin import kotlinx.datetime.* import kotlinx.datetime.format.* // Parse a partial format (month + day, no year) val monthDay = DateTimeComponents.Format { monthNumber(); char('/'); day() } val result = monthDay.parse("12/25") println(result.day) println(result.monthNumber) ``` -------------------------------- ### Convert Instant to LocalDateTime Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Convert a `kotlin.time.Instant` to a `LocalDateTime` using a specific `TimeZone`. The inverse operation is `LocalDateTime.toInstant(timeZone)`. Be mindful of Daylight Saving Time transitions. ```kotlin import kotlinx.datetime.* import kotlin.time.Clock import kotlin.time.Instant val instant: Instant = Instant.parse("2025-03-30T01:00:00Z") val tz = TimeZone.of("Europe/Berlin") // UTC+1 in winter, UTC+2 in summer val ldt: LocalDateTime = instant.toLocalDateTime(tz) println(ldt) // 2025-03-30T03:00 (DST spring-forward just occurred; +2) println(ldt.year) // 2025 println(ldt.month) // MARCH println(ldt.day) // 30 println(ldt.hour) // 3 println(ldt.minute) // 0 // Round-trip back to Instant val backToInstant: Instant = ldt.toInstant(tz) println(backToInstant == instant) // true ``` -------------------------------- ### Serialize kotlinx-datetime types with kotlinx-serialization Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Demonstrates how to serialize and deserialize kotlinx-datetime types using kotlinx-serialization. Requires explicit registration of TimeZoneSerializer for TimeZone types. ```kotlin import kotlinx.datetime.* import kotlinx.datetime.serializers.* import kotlinx.serialization.* import kotlinx.serialization.json.* // Default: serialized as ISO 8601 string @Serializable data class Event( val title: String, val date: LocalDate, val time: LocalTime, val scheduledAt: LocalDateTime, val validUntil: kotlin.time.Instant, val yearMonth: YearMonth, val tz: @Contextual TimeZone, ) val json = Json { serializersModule = SerializersModule { contextual(TimeZone::class, TimeZoneSerializer) }} val event = Event( title = "Launch", date = LocalDate(2025, 6, 1), time = LocalTime(14, 30), scheduledAt = LocalDateTime(2025, 6, 1, 14, 30), validUntil = kotlin.time.Instant.parse("2025-12-31T23:59:59Z"), yearMonth = YearMonth(2025, 6), tz = TimeZone.of("Europe/Berlin"), ) val serialized = json.encodeToString(event) // {"title":"Launch","date":"2025-06-01","time":"14:30","scheduledAt":"2025-06-01T14:30", // "validUntil":"2025-12-31T23:59:59Z","yearMonth":"2025-06","tz":"Europe/Berlin"} val restored = json.decodeFromString(serialized) println(restored.date == event.date) // true // Component-based serializer for LocalDate @Serializable data class BirthRecord( @Serializable(with = LocalDateComponentSerializer::class) val birthDate: LocalDate ) // Serializes as: {"birthDate":{"year":2025,"month":6,"day":1}} ``` -------------------------------- ### Add ZoneInfo Dependency for Wasm/WASI Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Include the kotlinx-datetime-zoneinfo dependency in your Gradle build script to enable full time zone support in Kotlin/Wasm WASI. ```kotlin kotlin { sourceSets { val wasmWasiMain by getting { dependencies { implementation("kotlinx-datetime-zoneinfo", "2026b-spi.0.8.0") } } } } ``` -------------------------------- ### Update Kotlin Compiler Server Version Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md Update the kotlinx-datetime version in the kotlin-compiler-server repository. ```toml kotlinx-datetime = "" ``` -------------------------------- ### Check Git Status Source: https://github.com/kotlin/kotlinx-datetime/blob/master/UPDATE_TIMEZONE_DATABASE.md Before updating, ensure there are no uncommitted changes in the timezone database directory. ```bash git status timezones/full/tzdb/ ``` -------------------------------- ### Using Optional Sections in LocalTime Formatting in Kotlin Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Defines a format for LocalTime that includes an optional seconds component. This allows parsing strings with or without seconds. ```kotlin import kotlinx.datetime.* import kotlinx.datetime.format.* // --- Optional sections --- val optionalSeconds = LocalTime.Format { hour(); char(':'); minute() optional { char(':'); second() } } println(optionalSeconds.parse("14:30")) println(optionalSeconds.parse("14:30:15")) ``` -------------------------------- ### Calculate Instant Arithmetic Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Perform arithmetic operations on `Instant` objects, such as adding or subtracting `Duration`. ```kotlin val now = Clock.System.now() val instantInThePast: Instant = Instant.parse("2020-01-01T00:00:00Z") val durationSinceThen: Duration = now - instantInThePast val equidistantInstantInTheFuture: Instant = now + durationSinceThen ``` -------------------------------- ### Convert Instant to LocalDateTime in a Specific TimeZone Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Converts an Instant to LocalDateTime in a specific time zone obtained by its string identifier. Requires TimeZone.of. ```kotlin val tzBerlin = TimeZone.of("Europe/Berlin") val datetimeInBerlin = currentMoment.toLocalDateTime(tzBerlin) ``` -------------------------------- ### Configure Kotlin/JS Time Zone Support Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md To enable full time zone support in Kotlin/JS, add the @js-joda/timezone npm dependency and initialize it. Replace 'X.X.X' with the latest version. ```kotlin kotlin { sourceSets { val jsMain by getting { dependencies { implementation(npm("@js-joda/timezone", "X.X.X")) } } } } ``` ```kotlin @JsModule("@js-joda/timezone") @JsNonModule external object JsJodaTimeZoneModule @OptIn(ExperimentalJsExport::class) @JsExport val jsJodaTz = JsJodaTimeZoneModule ``` -------------------------------- ### Construct and Format LocalDateTime in Kotlin Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Represents date + time components without a time zone. Primarily used for display, persistence of scheduled events, and as an intermediate step before/after Instant conversion. ```kotlin import kotlinx.datetime.* // Construction val meeting = LocalDateTime(2025, 11, 15, 14, 30, 0) // year, month, day, hour, minute, second val precise = LocalDateTime(2025, 11, 15, 14, 30, 0, 500_000_000) // with nanoseconds val fromParts = LocalDateTime(LocalDate(2025, 11, 15), LocalTime(14, 30)) // Null-safe construction val safe: LocalDateTime? = LocalDateTime.orNull(2025, 2, 30, 0, 0) // null — Feb 30 doesn't exist // Parse / format val parsed = LocalDateTime.parse("2025-11-15T14:30:00") println(parsed) // 2025-11-15T14:30 // Custom format val fmt = LocalDateTime.Format { date(LocalDate.Formats.ISO) char(' ') hour(); char(':'); minute() } println(fmt.format(meeting)) // "2025-11-15 14:30" println(fmt.parse("2025-11-15 14:30")) // LocalDateTime(2025,11,15,14,30,0,0) // Extract parts println(meeting.date) // 2025-11-15 println(meeting.time) // 14:30 println(meeting.dayOfWeek) // SATURDAY println(meeting.dayOfYear) // 319 ``` -------------------------------- ### Construct and Format LocalTime in Kotlin Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Represents a time of day with no date or time zone. Supports construction from ordinal values and parsing/formatting. ```kotlin import kotlinx.datetime.* // Construction val t = LocalTime(14, 30, 0) val precise = LocalTime(14, 30, 15, 123_000_000) val safe: LocalTime? = LocalTime.orNull(25, 0) // null — hour 25 invalid // From / to ordinal values val fromSec = LocalTime.fromSecondOfDay(3600) // 01:00 val fromMs = LocalTime.fromMillisecondOfDay(90_000) // 00:01:30 val fromNs = LocalTime.fromNanosecondOfDay(0L) // 00:00 println(t.toSecondOfDay()) // 52200 println(t.toNanosecondOfDay()) // 52200_000_000_000 // Parse / format val parsed = LocalTime.parse("14:30:15.123") println(LocalTime(9, 5).toString()) // "09:05" val hhmm = LocalTime.Format { hour(); char(':'); minute() } println(hhmm.format(t)) // "14:30" println(hhmm.parse("09:05")) // 09:05 // Combine with a date to get LocalDateTime val ldt: LocalDateTime = t.atDate(LocalDate(2025, 6, 1)) println(ldt) // 2025-06-01T14:30 ``` -------------------------------- ### Update Gradle Properties for Compatibility Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md Modify the gradle.properties file to include the compatibility version. ```properties version=-0.6.x-compat ``` -------------------------------- ### Update Release Label in kotlin-web-site Repository Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md Update the `KOTLINX_DATETIME_RELEASE_LABEL` in the `.teamcity/BuildParams.kt` file within the JetBrains/kotlin-web-site repository. ```plaintext Update `KOTLINX_DATETIME_RELEASE_LABEL` to `v` in . ``` -------------------------------- ### Format DateTimeComponents with Custom Values Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Use the format function on DateTimeComponents.Formats to construct and format data, including out-of-bounds values like 60 seconds, and apply offsets. ```kotlin DateTimeComponents.Formats.RFC_1123.format { // the receiver of this lambda is DateTimeComponents setDate(LocalDate(2023, 1, 7)) hour = 23 minute = 59 second = 60 setOffset(UtcOffset(hours = 2)) } // Sat, 7 Jan 2023 23:59:60 +0200 ``` -------------------------------- ### Maven Dependency for Kotlinx-datetime Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Add this dependency to your project's pom.xml to include the kotlinx-datetime library. Use the platform-specific -jvm artifact for Maven. ```xml org.jetbrains.kotlinx kotlinx-datetime-jvm 0.8.0 ``` -------------------------------- ### Convert LocalDateTime to Instant Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Obtains an Instant from a LocalDateTime by interpreting it as a time moment in a particular TimeZone. Requires TimeZone.of. ```kotlin val kotlinReleaseInstant = kotlinReleaseDateTime.toInstant(TimeZone.of("UTC+3")) ``` -------------------------------- ### Handling Out-of-Bounds Values with DateTimeComponents in Kotlin Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Illustrates how to parse a time with a leap second (60) and then adjust it to a valid second (59). Useful for handling edge cases in time parsing. ```kotlin import kotlinx.datetime.* import kotlinx.datetime.format.* // Handle out-of-bounds values (e.g. leap second 23:59:60) val leapTime = DateTimeComponents.Format { time(LocalTime.Formats.ISO) } .parse("23:59:60") .apply { if (second == 60) second = 59 } .toLocalTime() println(leapTime) ``` -------------------------------- ### Add JS Time Zone Dependency for Wasm/JS Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Configure your Gradle build script to include the JS time zone library for Wasm/JS projects. Replace X.X.X with the latest version. ```kotlin kotlin { sourceSets { val wasmJsMain by getting { dependencies { implementation(npm("@js-joda/timezone", "X.X.X")) } } } } ``` -------------------------------- ### Push Normal Release Branch Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md Push the changes for the normal release branch. ```git git push -u origin version--normal ``` -------------------------------- ### Calculate Difference in Specific DateTime Units Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Calculate the difference between two instants in a specific `DateTimeUnit` (e.g., months) within a given `TimeZone`. ```kotlin val diffInMonths = instantInThePast.until(Clock.System.now(), DateTimeUnit.MONTH, TimeZone.UTC) ``` -------------------------------- ### Custom LocalDateTime Formatting in Kotlin Source: https://context7.com/kotlin/kotlinx-datetime/llms.txt Defines a custom format for LocalDateTime combining ISO date and time formats, separated by a space. Useful for database storage or specific log formats. ```kotlin import kotlinx.datetime.* import kotlinx.datetime.format.* // --- LocalDateTime custom format (space-separated) --- val dbFormat = LocalDateTime.Format { date(LocalDate.Formats.ISO) char(' ') time(LocalTime.Formats.ISO) } println(dbFormat.format(LocalDateTime(2025, 6, 1, 14, 30))) ``` -------------------------------- ### Parse with Unicode Pattern String Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Use the byUnicodePattern function within a LocalDateTime.Format builder to parse strings matching a specified Unicode pattern. Requires opt-in for FormatStringsInDatetimeFormats. ```kotlin val formatPattern = "yyyy-MM-dd'T'HH:mm:ss[.SSS]" @OptIn(FormatStringsInDatetimeFormats::class) val dateTimeFormat = LocalDateTime.Format { byUnicodePattern(formatPattern) } dateTimeFormat.parse("2023-12-24T23:59:59") ``` -------------------------------- ### Parse Partial Date/Time Components Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Use DateTimeComponents.Format to parse strings that may not represent a full date or time, such as month and day. It can also parse and convert to specific types like UtcOffset or LocalDateTime. ```kotlin // import kotlinx.datetime.format.* val monthDay = DateTimeComponents.Format { monthNumber(); char('/'); day() } .parse("12/25") println(monthDay.day) // 25 println(monthDay.monthNumber) // 12 ``` ```kotlin val dateTimeOffset = DateTimeComponents.Formats.ISO_DATE_TIME_OFFSET .parse("2023-01-07T23:16:15.53+02:00") println(dateTimeOffset.toUtcOffset()) // +02:00 println(dateTimeOffset.toLocalDateTime()) // 2023-01-07T23:16:15.53 ``` -------------------------------- ### Merge Release into Master Source: https://github.com/kotlin/kotlinx-datetime/blob/master/RELEASE.md Merge the version branch into the master branch after successful deployments. ```git git checkout master git merge version- git push ``` -------------------------------- ### Commit Timezone Database Changes Source: https://github.com/kotlin/kotlinx-datetime/blob/master/UPDATE_TIMEZONE_DATABASE.md After updating the timezone database, commit the changes including the updated database files, gradle.properties, and README.md. ```bash git commit timezones/*/tzdb gradle.properties README.md -m 'Use IANA tzdb '; git push -u origin tzdb- ``` -------------------------------- ### Convert Unicode Format String to Kotlin Builder DSL Source: https://github.com/kotlin/kotlinx-datetime/blob/master/README.md Use DateTimeFormat.formatAsKotlinBuilderDsl to convert a Java-like Unicode pattern string into a Kotlin builder DSL format. This is useful for complex or non-standard formats. ```kotlin // import kotlinx.datetime.format.* println(DateTimeFormat.formatAsKotlinBuilderDsl(DateTimeComponents.Format { byUnicodePattern("uuuu-MM-dd'T'HH:mm:ss[.SSS]Z") })) // will print: /* date(LocalDate.Formats.ISO) char('T') hour() char(':') minute() char(':') second() alternativeParsing({ }) { char('.') secondFraction(3) } offset(UtcOffset.Formats.FOUR_DIGITS) */ ```