Kotlin / kotlinx-datetime

KotlinX multiplatform date/time library
Apache License 2.0
2.39k stars 99 forks source link

Plus an minus methods on `LocalTime` and `LocalDateTime` types #429

Closed nesk closed 1 month ago

nesk commented 1 month ago

The Instant type supports addition and subtraction of a Duration:

fun example(now: Instant) {
    now - 5.seconds
    now + 5.seconds
}

The LocalDate type supports addition and subtraction of DatePeriod:

fun example(now: LocalDate) {
    now - DatePeriod(days = 2)
    now + DatePeriod(days = 2)
}

However, the LocalTime doesn't support any addition or subtraction, which requires cumbersome code to do these changes:

fun example(now: LocalTime) {
    LocalTime.fromSecondOfDay(now.toSecondOfDay() - 5)
    LocalTime.fromSecondOfDay(now.toSecondOfDay() + 5)
}

What about adding a TimePeriod type? This would allow to write code like this:

fun example(now: LocalTime) {
    now - TimePeriod(seconds = 5)
    now + TimePeriod(seconds = 5)
}

This would also pave the way for addition and subtraction of the LocalDateTime type:

fun example(now: LocalDateTime) {
    now - DateTimePeriod(days = 2, seconds = 5)
    now + DateTimePeriod(days = 2, seconds = 5)
}
dkhalanskyjb commented 1 month ago

Please read https://github.com/Kotlin/kotlinx-datetime?tab=readme-ov-file#date--time-arithmetic

If you have some specific code that needs LocalTime arithmetics, please share it here or on the Kotlin Slack, and we'll help you reach an idiomatic and robust solution.

nesk commented 1 month ago

Sorry, I did not see this section in the documentation 😓

Seems fine to me, I will use Instant for arithmetics!