is there a util function for adding a <Duration> t...
# kotlinx-datetime
a
is there a util function for adding a Duration to a LocalDate or LocalDateTime?
e
that wouldn't have a well-defined result at DST changes and other timezone definition changes
if you don't care about that, I suppose you could
Copy code
localDateTime.toInstant(TimeZone.UTC).plus(duration).toLocalDateTime(TimeZone.UTC)
but it raises the question of why would you be doing these operations with a
Local*
instead of an
Instant
?
a
cool thanks, that seems to work
Copy code
operator fun LocalDate.plus(duration: Duration): LocalDate =
    atStartOfDayIn(TimeZone.UTC).plus(duration).toLocalDateTime(TimeZone.UTC).date

operator fun LocalDateTime.plus(duration: Duration): LocalDateTime =
    toInstant(TimeZone.UTC).plus(duration).toLocalDateTime(TimeZone.UTC)
but it raises the question of why would you be doing these operations with a
Local*
instead of an
Instant
?
I’m updating some Java time code. My experience in Java is that Instant is awkward and difficult to use, but maybe my prejudice doesn’t apply to a Kotlin Instant?
e
LocalDateTime + Duration is not something that can be done without knowing the TimeZone. 2023-03-12 01:30 + 1 hour = 2:30 in most parts of the world but 3:30 in most parts of the US
yes, Instant can be awkward when you want human times, but human times are a pain. you need Instant or ZonedDateTime (which kotlinx-datetime doesn't have) to actually perform most operations.
s
@ephemient so you can't actually perform most operations in KotlinX date-time?
e
how do you get that from what I said?
kotlinx-datetime has TimeZone and Instant which is all a ZonedDateTime really is
s
https://kotlinlang.slack.com/archives/C01923PC6A0/p1688909668283709?thread_ts=1688900739.162529&amp;cid=C01923PC6A0
you need ... ZonedDateTime (which kotlinx-datetime doesn't have) to actually perform most operations.
a
I would read that as: you need Instant (if using kotlinx-datetime or
java.time
) or ZDT (if using
java.time
) to perform most operations
e
obviously both kotlinx-datetime and java.time have Instant. only java.time has ZDT, but it is mostly isomorphic to a pair of (Instant, ZoneId), and you don't need another structure to do that in Kotlin.