-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathLocalDate.kt
536 lines (493 loc) · 22.5 KB
/
LocalDate.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
/*
* Copyright 2019-2022 JetBrains s.r.o. and contributors.
* Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file.
*/
package kotlinx.datetime
import kotlinx.datetime.format.*
import kotlinx.datetime.serializers.*
import kotlinx.serialization.Serializable
/**
* The date part of [LocalDateTime].
*
* This class represents dates without a reference to a particular time zone.
* As such, these objects may denote different time intervals in different time zones: for someone in Berlin,
* `2020-08-30` started and ended at different moments from those for someone in Tokyo.
*
* The arithmetic on [LocalDate] values is defined independently of the time zone (so `2020-08-30` plus one day
* is `2020-08-31` everywhere): see various [LocalDate.plus] and [LocalDate.minus] functions, as well
* as [LocalDate.periodUntil] and various other [*until][LocalDate.daysUntil] functions.
*
* ### Arithmetic operations
*
* Operations with [DateTimeUnit.DateBased] and [DatePeriod] are provided for [LocalDate]:
* - [LocalDate.plus] and [LocalDate.minus] allow expressing concepts like "two months later".
* - [LocalDate.until] and its shortcuts [LocalDate.daysUntil], [LocalDate.monthsUntil], and [LocalDate.yearsUntil]
* can be used to find the number of days, months, or years between two dates.
* - [LocalDate.periodUntil] (and [LocalDate.minus] that accepts a [LocalDate])
* can be used to find the [DatePeriod] between two dates.
*
* ### Platform specifics
*
* The range of supported years is platform-dependent, but at least is enough to represent dates of all instants between
* [Instant.DISTANT_PAST] and [Instant.DISTANT_FUTURE].
*
* On the JVM,
* there are `LocalDate.toJavaLocalDate()` and `java.time.LocalDate.toKotlinLocalDate()`
* extension functions to convert between `kotlinx.datetime` and `java.time` objects used for the same purpose.
* Similarly, on the Darwin platforms, there is a `LocalDate.toNSDateComponents()` extension function.
*
* ### Construction, serialization, and deserialization
*
* [LocalDate] can be constructed directly from its components using the constructor.
* See sample 1.
*
* [fromEpochDays] can be used to obtain a [LocalDate] from the number of days since the epoch day `1970-01-01`;
* [toEpochDays] is the inverse operation.
* See sample 2.
*
* [parse] and [toString] methods can be used to obtain a [LocalDate] from and convert it to a string in the
* ISO 8601 extended format.
* See sample 3.
*
* [parse] and [LocalDate.format] both support custom formats created with [Format] or defined in [Formats].
* See sample 4.
*
* Additionally, there are several `kotlinx-serialization` serializers for [LocalDate]:
* - [LocalDateIso8601Serializer] for the ISO 8601 extended format.
* - [LocalDateComponentSerializer] for an object with components.
*
* @sample kotlinx.datetime.test.samples.LocalDateSamples.constructorFunctionMonthNumber
* @sample kotlinx.datetime.test.samples.LocalDateSamples.fromAndToEpochDays
* @sample kotlinx.datetime.test.samples.LocalDateSamples.simpleParsingAndFormatting
* @sample kotlinx.datetime.test.samples.LocalDateSamples.customFormat
*/
@Serializable(with = LocalDateIso8601Serializer::class)
public expect class LocalDate : Comparable<LocalDate> {
public companion object {
/**
* A shortcut for calling [DateTimeFormat.parse].
*
* Parses a string that represents a date and returns the parsed [LocalDate] value.
*
* If [format] is not specified, [Formats.ISO] is used.
* `2023-01-02` is an example of a string in this format.
*
* @throws IllegalArgumentException if the text cannot be parsed or the boundaries of [LocalDate] are exceeded.
*
* @see LocalDate.toString for formatting using the default format.
* @see LocalDate.format for formatting using a custom format.
* @sample kotlinx.datetime.test.samples.LocalDateSamples.parsing
*/
public fun parse(input: CharSequence, format: DateTimeFormat<LocalDate> = getIsoDateFormat()): LocalDate
/**
* Returns a [LocalDate] that is [epochDays] number of days from the epoch day `1970-01-01`.
*
* @throws IllegalArgumentException if the result exceeds the platform-specific boundaries of [LocalDate].
* @see LocalDate.toEpochDays
* @sample kotlinx.datetime.test.samples.LocalDateSamples.fromAndToEpochDays
*/
public fun fromEpochDays(epochDays: Int): LocalDate
/**
* Returns a [LocalDate] that is [epochDays] number of days from the epoch day `1970-01-01`.
*
* @throws IllegalArgumentException if the result exceeds the platform-specific boundaries of [LocalDate].
* @see LocalDate.toEpochDaysLong
* @sample kotlinx.datetime.test.samples.LocalDateSamples.fromAndToEpochDays
*/
internal fun fromEpochDays(epochDays: Long): LocalDate
/**
* Creates a new format for parsing and formatting [LocalDate] values.
*
* Only parsing and formatting of well-formed values is supported. If the input does not fit the boundaries
* (for example, [dayOfMonth] is 31 for February), consider using [DateTimeComponents.Format] instead.
*
* There is a collection of predefined formats in [LocalDate.Formats].
*
* @throws IllegalArgumentException if parsing using this format is ambiguous.
* @sample kotlinx.datetime.test.samples.LocalDateSamples.customFormat
*/
@Suppress("FunctionName")
public fun Format(block: DateTimeFormatBuilder.WithDate.() -> Unit): DateTimeFormat<LocalDate>
internal val MIN: LocalDate
internal val MAX: LocalDate
}
/**
* A collection of predefined formats for parsing and formatting [LocalDate] values.
*
* See [LocalDate.Formats.ISO] and [LocalDate.Formats.ISO_BASIC] for popular predefined formats.
* [LocalDate.parse] and [LocalDate.toString] can be used as convenient shortcuts for the
* [LocalDate.Formats.ISO] format.
*
* If predefined formats are not sufficient, use [LocalDate.Format] to create a custom
* [kotlinx.datetime.format.DateTimeFormat] for [LocalDate] values.
*/
public object Formats {
/**
* ISO 8601 extended format, which is the format used by [LocalDate.toString] and [LocalDate.parse].
*
* Examples of dates in ISO 8601 format:
* - `2020-08-30`
* - `+12020-08-30`
* - `0000-08-30`
* - `-0001-08-30`
*
* See ISO-8601-1:2019, 5.2.2.1b), using the "expanded calendar year" extension from 5.2.2.3a), generalized
* to any number of digits in the year for years that fit in an [Int].
*
* @sample kotlinx.datetime.test.samples.LocalDateSamples.Formats.iso
*/
public val ISO: DateTimeFormat<LocalDate>
/**
* ISO 8601 basic format.
*
* Examples of dates in ISO 8601 basic format:
* - `20200830`
* - `+120200830`
* - `00000830`
* - `-00010830`
*
* See ISO-8601-1:2019, 5.2.2.1a), using the "expanded calendar year" extension from 5.2.2.3a), generalized
* to any number of digits in the year for years that fit in an [Int].
*
* @sample kotlinx.datetime.test.samples.LocalDateSamples.Formats.isoBasic
*/
public val ISO_BASIC: DateTimeFormat<LocalDate>
}
/**
* Constructs a [LocalDate] instance from the given date components.
*
* The components [monthNumber] and [dayOfMonth] are 1-based.
*
* The supported ranges of components:
* - [year] the range is platform-dependent, but at least is enough to represent dates of all instants between
* [Instant.DISTANT_PAST] and [Instant.DISTANT_FUTURE]
* - [monthNumber] `1..12`
* - [dayOfMonth] `1..31`, the upper bound can be less, depending on the month
*
* @throws IllegalArgumentException if any parameter is out of range or if [dayOfMonth] is invalid for the
* given [monthNumber] and [year].
* @sample kotlinx.datetime.test.samples.LocalDateSamples.constructorFunctionMonthNumber
*/
public constructor(year: Int, monthNumber: Int, dayOfMonth: Int)
/**
* Constructs a [LocalDate] instance from the given date components.
*
* The supported ranges of components:
* - [year] the range is platform-dependent, but at least is enough to represent dates of all instants between
* [Instant.DISTANT_PAST] and [Instant.DISTANT_FUTURE]
* - [month] all values of the [Month] enum
* - [dayOfMonth] `1..31`, the upper bound can be less, depending on the month
*
* @throws IllegalArgumentException if any parameter is out of range or if [dayOfMonth] is invalid for the
* given [month] and [year].
* @sample kotlinx.datetime.test.samples.LocalDateSamples.constructorFunction
*/
public constructor(year: Int, month: Month, dayOfMonth: Int)
/**
* Returns the year component of the date.
*
* @sample kotlinx.datetime.test.samples.LocalDateSamples.year
*/
public val year: Int
/**
* Returns the number-of-the-month (1..12) component of the date.
*
* Shortcut for `month.number`.
*/
public val monthNumber: Int
/**
* Returns the month ([Month]) component of the date.
*
* @sample kotlinx.datetime.test.samples.LocalDateSamples.month
*/
public val month: Month
/**
* Returns the day-of-month (`1..31`) component of the date.
*
* @sample kotlinx.datetime.test.samples.LocalDateSamples.dayOfMonth
*/
public val dayOfMonth: Int
/**
* Returns the day-of-week component of the date.
*
* @sample kotlinx.datetime.test.samples.LocalDateSamples.dayOfWeek
*/
public val dayOfWeek: DayOfWeek
/**
* Returns the day-of-year (`1..366`) component of the date.
*
* @sample kotlinx.datetime.test.samples.LocalDateSamples.dayOfYear
*/
public val dayOfYear: Int
/**
* Returns the number of days since the epoch day `1970-01-01`.
*
* If the result does not fit in [Int], returns [Int.MAX_VALUE] for a positive result or [Int.MIN_VALUE] for a negative result.
*
* @see LocalDate.fromEpochDays
* @sample kotlinx.datetime.test.samples.LocalDateSamples.toEpochDays
*/
public fun toEpochDays(): Int
/**
* Returns the number of days since the epoch day `1970-01-01`.
*
* If the result does not fit in [Long], returns [Long.MAX_VALUE] for a positive result or [Long.MIN_VALUE] for a negative result.
*
* @see LocalDate.fromEpochDays
* @sample kotlinx.datetime.test.samples.LocalDateSamples.toEpochDays
*/
internal fun toEpochDaysLong(): Long
/**
* Compares `this` date with the [other] date.
* Returns zero if this date represents the same day as the other (meaning they are equal to one other),
* a negative number if this date is earlier than the other,
* and a positive number if this date is later than the other.
*
* @sample kotlinx.datetime.test.samples.LocalDateSamples.compareToSample
*/
public override fun compareTo(other: LocalDate): Int
/**
* Converts this date to the extended ISO 8601 string representation.
*
* @see Formats.ISO for the format details.
* @see parse for the dual operation: obtaining [LocalDate] from a string.
* @see LocalDate.format for formatting using a custom format.
* @sample kotlinx.datetime.test.samples.LocalDateSamples.toStringSample
*/
public override fun toString(): String
/**
* Creates a [LocalDateRange] from `this` to [that], inclusive.
*
* @sample kotlinx.datetime.test.samples.LocalDateRangeSamples.simpleRangeCreation
*/
public operator fun rangeTo(that: LocalDate): LocalDateRange
/**
* Creates a [LocalDateRange] from `this` to [that], exclusive. i.e. from this to (that - 1 day)
*
* @sample kotlinx.datetime.test.samples.LocalDateRangeSamples.simpleRangeCreation
*/
public operator fun rangeUntil(that: LocalDate) : LocalDateRange
}
/**
* Formats this value using the given [format].
* Equivalent to calling [DateTimeFormat.format] on [format] with `this`.
*
* @sample kotlinx.datetime.test.samples.LocalDateSamples.formatting
*/
public fun LocalDate.format(format: DateTimeFormat<LocalDate>): String = format.format(this)
/**
* @suppress
*/
@Deprecated("Removed to support more idiomatic code. See https://github.com/Kotlin/kotlinx-datetime/issues/339", ReplaceWith("LocalDate.parse(this)"), DeprecationLevel.WARNING)
public fun String.toLocalDate(): LocalDate = LocalDate.parse(this)
/**
* Combines this date's components with the specified time components into a [LocalDateTime] value.
*
* For finding an instant that corresponds to the start of a date in a particular time zone, consider using
* [LocalDate.atStartOfDayIn] function because a day does not always start at the fixed time 0:00:00.
*
* **Pitfall**: since [LocalDateTime] is not tied to a particular time zone, the resulting [LocalDateTime] may not
* exist in the implicit time zone.
* For example, `LocalDate(2021, 3, 28).atTime(2, 16, 20)` will successfully create a [LocalDateTime],
* even though in Berlin, times between 2:00 and 3:00 do not exist on March 28, 2021 due to the transition to DST.
*
* @sample kotlinx.datetime.test.samples.LocalDateSamples.atTimeInline
*/
public fun LocalDate.atTime(hour: Int, minute: Int, second: Int = 0, nanosecond: Int = 0): LocalDateTime =
LocalDateTime(year, monthNumber, dayOfMonth, hour, minute, second, nanosecond)
/**
* Combines this date's components with the specified [LocalTime] components into a [LocalDateTime] value.
*
* For finding an instant that corresponds to the start of a date in a particular time zone consider using
* [LocalDate.atStartOfDayIn] function because a day does not always start at the fixed time 0:00:00.
*
* **Pitfall**: since [LocalDateTime] is not tied to a particular time zone, the resulting [LocalDateTime] may not
* exist in the implicit time zone.
* For example, `LocalDate(2021, 3, 28).atTime(LocalTime(2, 16, 20))` will successfully create a [LocalDateTime],
* even though in Berlin, times between 2:00 and 3:00 do not exist on March 28, 2021, due to the transition to DST.
*
* @sample kotlinx.datetime.test.samples.LocalDateSamples.atTime
*/
public fun LocalDate.atTime(time: LocalTime): LocalDateTime = LocalDateTime(this, time)
/**
* Returns a date that results from adding components of [DatePeriod] to this date. The components are
* added in the order from the largest units to the smallest: first years and months, then days.
*
* @see LocalDate.periodUntil
* @throws DateTimeArithmeticException if this value or the results of intermediate computations are too large to fit in
* [LocalDate].
* @sample kotlinx.datetime.test.samples.LocalDateSamples.plusPeriod
*/
public expect operator fun LocalDate.plus(period: DatePeriod): LocalDate
/**
* Returns a date that results from subtracting components of [DatePeriod] from this date. The components are
* subtracted in the order from the largest units to the smallest: first years and months, then days.
*
* @see LocalDate.periodUntil
* @throws DateTimeArithmeticException if this value or the results of intermediate computations are too large to fit in
* [LocalDate].
* @sample kotlinx.datetime.test.samples.LocalDateSamples.minusPeriod
*/
public operator fun LocalDate.minus(period: DatePeriod): LocalDate =
if (period.days != Int.MIN_VALUE && period.months != Int.MIN_VALUE) {
plus(with(period) { DatePeriod(-years, -months, -days) })
} else {
// TODO: calendar operations are non-associative; check if subtracting years and months separately is correct
minus(period.years, DateTimeUnit.YEAR).minus(period.months, DateTimeUnit.MONTH)
.minus(period.days, DateTimeUnit.DAY)
}
/**
* Returns a [DatePeriod] representing the difference between `this` and [other] dates.
*
* The components of [DatePeriod] are calculated so that adding it to `this` date results in the [other] date.
*
* All components of the [DatePeriod] returned are:
* - Positive or zero if this date is earlier than the other.
* - Negative or zero if this date is later than the other.
* - Exactly zero if this date is equal to the other.
*
* @throws DateTimeArithmeticException if the number of months between the two dates exceeds an Int (JVM only).
*
* @see LocalDate.minus for the same operation with the order of arguments reversed.
* @sample kotlinx.datetime.test.samples.LocalDateSamples.periodUntil
*/
public expect fun LocalDate.periodUntil(other: LocalDate): DatePeriod
/**
* Returns a [DatePeriod] representing the difference between [other] and `this` dates.
*
* The components of [DatePeriod] are calculated so that adding it back to the `other` date results in this date.
*
* All components of the [DatePeriod] returned are:
* - Negative or zero if this date is earlier than the other.
* - Positive or zero if this date is later than the other.
* - Exactly zero if this date is equal to the other.
*
* @throws DateTimeArithmeticException if the number of months between the two dates exceeds an Int (JVM only).
*
* @see LocalDate.periodUntil for the same operation with the order of arguments reversed.
* @sample kotlinx.datetime.test.samples.LocalDateSamples.minusDate
*/
public operator fun LocalDate.minus(other: LocalDate): DatePeriod = other.periodUntil(this)
/**
* Returns the whole number of the specified date [units][unit] between `this` and [other] dates.
*
* The value returned is:
* - Positive or zero if this date is earlier than the other.
* - Negative or zero if this date is later than the other.
* - Zero if this date is equal to the other.
*
* The value is rounded toward zero.
*
* If the result does not fit in [Int], returns [Int.MAX_VALUE] for a positive result or [Int.MIN_VALUE] for a negative result.
*
* @see LocalDate.daysUntil
* @see LocalDate.monthsUntil
* @see LocalDate.yearsUntil
* @sample kotlinx.datetime.test.samples.LocalDateSamples.until
*/
public expect fun LocalDate.until(other: LocalDate, unit: DateTimeUnit.DateBased): Int
/**
* Returns the number of whole days between two dates.
*
* The value is rounded toward zero.
*
* If the result does not fit in [Int], returns [Int.MAX_VALUE] for a positive result or [Int.MIN_VALUE] for a negative result.
*
* @see LocalDate.until
* @sample kotlinx.datetime.test.samples.LocalDateSamples.daysUntil
*/
public expect fun LocalDate.daysUntil(other: LocalDate): Int
/**
* Returns the number of whole months between two dates.
*
* The value is rounded toward zero.
*
* If the result does not fit in [Int], returns [Int.MAX_VALUE] for a positive result or [Int.MIN_VALUE] for a negative result.
*
* @see LocalDate.until
* @sample kotlinx.datetime.test.samples.LocalDateSamples.monthsUntil
*/
public expect fun LocalDate.monthsUntil(other: LocalDate): Int
/**
* Returns the number of whole years between two dates.
*
* The value is rounded toward zero.
*
* If the result does not fit in [Int], returns [Int.MAX_VALUE] for a positive result or [Int.MIN_VALUE] for a negative result.
*
* @see LocalDate.until
* @sample kotlinx.datetime.test.samples.LocalDateSamples.yearsUntil
*/
public expect fun LocalDate.yearsUntil(other: LocalDate): Int
/**
* Returns a [LocalDate] that results from adding one [unit] to this date.
*
* The value is rounded toward zero.
*
* The returned date is later than this date.
*
* @throws DateTimeArithmeticException if the result exceeds the boundaries of [LocalDate].
*/
@Deprecated("Use the plus overload with an explicit number of units", ReplaceWith("this.plus(1, unit)"))
public expect fun LocalDate.plus(unit: DateTimeUnit.DateBased): LocalDate
/**
* Returns a [LocalDate] that results from subtracting one [unit] from this date.
*
* The value is rounded toward zero.
*
* The returned date is earlier than this date.
*
* @throws DateTimeArithmeticException if the result exceeds the boundaries of [LocalDate].
*/
@Deprecated("Use the minus overload with an explicit number of units", ReplaceWith("this.minus(1, unit)"))
public fun LocalDate.minus(unit: DateTimeUnit.DateBased): LocalDate = plus(-1, unit)
/**
* Returns a [LocalDate] that results from adding the [value] number of the specified [unit] to this date.
*
* If the [value] is positive, the returned date is later than this date.
* If the [value] is negative, the returned date is earlier than this date.
*
* The value is rounded toward zero.
*
* @throws DateTimeArithmeticException if the result exceeds the boundaries of [LocalDate].
* @sample kotlinx.datetime.test.samples.LocalDateSamples.plus
*/
public expect fun LocalDate.plus(value: Int, unit: DateTimeUnit.DateBased): LocalDate
/**
* Returns a [LocalDate] that results from subtracting the [value] number of the specified [unit] from this date.
*
* If the [value] is positive, the returned date is earlier than this date.
* If the [value] is negative, the returned date is later than this date.
*
* The value is rounded toward zero.
*
* @throws DateTimeArithmeticException if the result exceeds the boundaries of [LocalDate].
* @sample kotlinx.datetime.test.samples.LocalDateSamples.minus
*/
public expect fun LocalDate.minus(value: Int, unit: DateTimeUnit.DateBased): LocalDate
/**
* Returns a [LocalDate] that results from adding the [value] number of the specified [unit] to this date.
*
* If the [value] is positive, the returned date is later than this date.
* If the [value] is negative, the returned date is earlier than this date.
*
* The value is rounded toward zero.
*
* @throws DateTimeArithmeticException if the result exceeds the boundaries of [LocalDate].
* @sample kotlinx.datetime.test.samples.LocalDateSamples.plus
*/
public expect fun LocalDate.plus(value: Long, unit: DateTimeUnit.DateBased): LocalDate
/**
* Returns a [LocalDate] that results from subtracting the [value] number of the specified [unit] from this date.
*
* If the [value] is positive, the returned date is earlier than this date.
* If the [value] is negative, the returned date is later than this date.
*
* The value is rounded toward zero.
*
* @throws DateTimeArithmeticException if the result exceeds the boundaries of [LocalDate].
* @sample kotlinx.datetime.test.samples.LocalDateSamples.minus
*/
public fun LocalDate.minus(value: Long, unit: DateTimeUnit.DateBased): LocalDate = plus(-value, unit)
// A workaround for https://youtrack.jetbrains.com/issue/KT-65484
internal fun getIsoDateFormat() = LocalDate.Formats.ISO