0
# kotlinx-datetime
1
2
A multiplatform Kotlin library for working with date and time that provides types for representing date and time values with clear separation between physical time instants and civil time components. Based on ISO 8601 standards with comprehensive formatting, serialization, and JVM interoperability support.
3
4
## Package Information
5
6
- **Package Name**: org.jetbrains.kotlinx:kotlinx-datetime-jvm
7
- **Package Type**: maven
8
- **Language**: Kotlin
9
- **Installation**: Add to your Gradle dependencies:
10
```kotlin
11
implementation("org.jetbrains.kotlinx:kotlinx-datetime-jvm:0.7.0")
12
```
13
14
## Core Imports
15
16
```kotlin
17
import kotlinx.datetime.*
18
import kotlinx.datetime.format.*
19
import kotlinx.datetime.serializers.*
20
import kotlin.time.Duration
21
```
22
23
## Basic Usage
24
25
```kotlin
26
import kotlinx.datetime.*
27
import kotlin.time.Duration.Companion.days
28
import kotlin.time.Duration.Companion.hours
29
30
// Get current instant and convert to local date-time
31
val now = Clock.System.now()
32
val localDateTime = now.toLocalDateTime(TimeZone.currentSystemDefault())
33
34
// Create specific dates and times
35
val date = LocalDate(2023, 12, 25) // Christmas 2023
36
val time = LocalTime(14, 30) // 2:30 PM
37
val dateTime = LocalDateTime(date, time)
38
val yearMonth = YearMonth(2024, 3) // March 2024
39
40
// Date arithmetic
41
val futureDate = date.plus(30, DateTimeUnit.DAY)
42
val daysBetween = date.daysUntil(futureDate)
43
44
// Convert to instant with timezone
45
val instant = dateTime.toInstant(TimeZone.of("America/New_York"))
46
47
// Format dates and times
48
val formattedDate = date.format(LocalDate.Formats.ISO) // "2023-12-25"
49
val formattedDateTime = dateTime.format(LocalDateTime.Formats.ISO) // "2023-12-25T14:30:00"
50
```
51
52
## Architecture
53
54
kotlinx-datetime is built around several key concepts:
55
56
- **Physical Time**: `Instant` represents a specific moment in time, independent of time zones
57
- **Civil Time**: `LocalDate`, `LocalTime`, and `LocalDateTime` represent calendar concepts without time zone context
58
- **Time Zones**: `TimeZone` provides conversion between physical and civil time with full timezone rules support
59
- **Periods & Units**: Flexible arithmetic operations with `DateTimePeriod`, `DatePeriod`, and `DateTimeUnit`
60
- **Format System**: Comprehensive parsing and formatting with builder DSL and predefined formats
61
- **Type Safety**: Immutable value types with clear boundaries and compile-time guarantees
62
- **Interoperability**: Seamless conversion to/from `java.time` types for JVM integration
63
64
## Capabilities
65
66
### Core Types & Operations
67
68
Essential date and time types with arithmetic operations, conversions, and timezone handling. Provides the foundation for all datetime operations.
69
70
```kotlin { .api }
71
// Physical time - specific moment in time
72
class Instant
73
74
// Civil time components - calendar concepts without timezone
75
data class LocalDate(val year: Int, val month: Month, val dayOfMonth: Int)
76
data class LocalTime(val hour: Int, val minute: Int, val second: Int = 0, val nanosecond: Int = 0)
77
data class LocalDateTime(val date: LocalDate, val time: LocalTime)
78
data class YearMonth(val year: Int, val month: Month)
79
80
// UTC offset and timezone handling
81
class UtcOffset(hours: Int, minutes: Int = 0)
82
abstract class TimeZone {
83
val id: String
84
companion object {
85
val UTC: TimeZone
86
fun of(zoneId: String): TimeZone
87
fun currentSystemDefault(): TimeZone
88
val availableZoneIds: Set<String>
89
}
90
}
91
92
// Clock extensions
93
fun Clock.todayIn(timeZone: TimeZone): LocalDate
94
95
// Enumerations
96
enum class Month { JANUARY, FEBRUARY, /* ... */ DECEMBER }
97
enum class DayOfWeek { MONDAY, TUESDAY, /* ... */ SUNDAY }
98
```
99
100
[Core Types & Operations](./core-types.md)
101
102
### Periods & Units
103
104
Period representations and arithmetic units for flexible date and time calculations. Essential for adding/subtracting time intervals and measuring differences.
105
106
```kotlin { .api }
107
// Period with date and time components
108
data class DateTimePeriod(
109
val years: Int = 0,
110
val months: Int = 0,
111
val days: Int = 0,
112
val hours: Int = 0,
113
val minutes: Int = 0,
114
val seconds: Int = 0,
115
val nanoseconds: Long = 0
116
)
117
118
// Period with only date components
119
data class DatePeriod(val years: Int = 0, val months: Int = 0, val days: Int = 0)
120
121
// Units for arithmetic operations
122
sealed class DateTimeUnit {
123
sealed class TimeBased : DateTimeUnit()
124
sealed class DateBased : DateTimeUnit()
125
126
companion object {
127
val NANOSECOND: TimeBased
128
val SECOND: TimeBased
129
val MINUTE: TimeBased
130
val HOUR: TimeBased
131
val DAY: DateBased
132
val MONTH: DateBased
133
val YEAR: DateBased
134
}
135
}
136
```
137
138
[Periods & Units](./periods-units.md)
139
140
### Formatting System
141
142
Comprehensive parsing and formatting system with builder DSL, predefined formats, and custom format creation. Supports all datetime types with locale-aware formatting.
143
144
```kotlin { .api }
145
// Base format interface
146
sealed interface DateTimeFormat<T> {
147
fun format(value: T): String
148
fun parse(input: CharSequence): T
149
fun parseOrNull(input: CharSequence): T?
150
}
151
152
// Format builders for each type
153
fun LocalDate.Companion.Format(block: DateTimeFormatBuilder.WithDate.() -> Unit): DateTimeFormat<LocalDate>
154
fun LocalTime.Companion.Format(block: DateTimeFormatBuilder.WithTime.() -> Unit): DateTimeFormat<LocalTime>
155
fun LocalDateTime.Companion.Format(block: DateTimeFormatBuilder.WithDateTime.() -> Unit): DateTimeFormat<LocalDateTime>
156
157
// Predefined formats
158
object LocalDate.Formats {
159
val ISO: DateTimeFormat<LocalDate>
160
}
161
object LocalDateTime.Formats {
162
val ISO: DateTimeFormat<LocalDateTime>
163
}
164
```
165
166
[Formatting System](./formatting.md)
167
168
### Serialization Support
169
170
Complete serialization support for all datetime types with both ISO 8601 string format and component-based JSON object serialization. Integrates with kotlinx.serialization.
171
172
```kotlin { .api }
173
// ISO 8601 string serializers
174
object InstantIso8601Serializer : KSerializer<Instant>
175
object LocalDateIso8601Serializer : KSerializer<LocalDate>
176
object LocalTimeIso8601Serializer : KSerializer<LocalTime>
177
object LocalDateTimeIso8601Serializer : KSerializer<LocalDateTime>
178
object TimeZoneSerializer : KSerializer<TimeZone>
179
180
// Component serializers (JSON objects)
181
object LocalDateComponentSerializer : KSerializer<LocalDate>
182
object LocalTimeComponentSerializer : KSerializer<LocalTime>
183
object LocalDateTimeComponentSerializer : KSerializer<LocalDateTime>
184
object DateTimePeriodComponentSerializer : KSerializer<DateTimePeriod>
185
```
186
187
[Serialization Support](./serialization.md)
188
189
### JVM Interoperability
190
191
Bidirectional converter functions for seamless integration with existing Java codebases using `java.time` types. Provides zero-overhead conversion between kotlinx-datetime and java.time.
192
193
```kotlin { .api }
194
// LocalDate converters
195
fun LocalDate.toJavaLocalDate(): java.time.LocalDate
196
fun java.time.LocalDate.toKotlinLocalDate(): LocalDate
197
198
// LocalTime converters
199
fun LocalTime.toJavaLocalTime(): java.time.LocalTime
200
fun java.time.LocalTime.toKotlinLocalTime(): LocalTime
201
202
// LocalDateTime converters
203
fun LocalDateTime.toJavaLocalDateTime(): java.time.LocalDateTime
204
fun java.time.LocalDateTime.toKotlinLocalDateTime(): LocalDateTime
205
206
// Instant converters
207
fun Instant.toJavaInstant(): java.time.Instant
208
fun java.time.Instant.toKotlinInstant(): Instant
209
210
// TimeZone converters
211
fun TimeZone.toJavaZoneId(): java.time.ZoneId
212
fun java.time.ZoneId.toKotlinTimeZone(): TimeZone
213
```
214
215
[JVM Interoperability](./jvm-interop.md)
216
217
## Exception Types
218
219
kotlinx-datetime defines specific exception types for different error conditions:
220
221
```kotlin { .api }
222
// Arithmetic overflow or bounds errors
223
class DateTimeArithmeticException : IllegalArgumentException
224
225
// Invalid timezone operations
226
class IllegalTimeZoneException : IllegalArgumentException
227
```