compare To
Compares this
date/time value with the other date/time value. Returns zero if this value is equal to the other, a negative number if this value represents earlier civil time than the other, and a positive number if this value represents later civil time than the other.
Pitfall: comparing LocalDateTime values is less robust than comparing Instant values. Consider the following situation, where a later moment in time corresponds to an earlier LocalDateTime value:
val zone = TimeZone.of("Europe/Berlin")
val ldt1 = Clock.System.now().toLocalDateTime(zone) // 2021-10-31T02:16:20
// 45 minutes pass; clocks move back from 03:00 to 02:00 in the meantime
val ldt2 = Clock.System.now().toLocalDateTime(zone) // 2021-10-31T02:01:20
ldt2 ldt1 // Returns `false`
Content copied to clipboard
Samples
import kotlinx.datetime.*
import kotlinx.datetime.format.*
import kotlin.test.*
fun main() {
//sampleStart
// Comparing LocalDateTime values
val date = LocalDate(2024, 2, 15)
val laterDate = LocalDate(2024, 2, 16)
check(date.atTime(hour = 23, minute = 59) < laterDate.atTime(hour = 0, minute = 0))
check(date.atTime(hour = 8, minute = 30) < date.atTime(hour = 17, minute = 10))
check(date.atTime(hour = 8, minute = 30) < date.atTime(hour = 8, minute = 31))
check(date.atTime(hour = 8, minute = 30) < date.atTime(hour = 8, minute = 30, second = 1))
check(date.atTime(hour = 8, minute = 30) < date.atTime(hour = 8, minute = 30, second = 0, nanosecond = 1))
//sampleEnd
}