Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Plus an minus methods on LocalTime and LocalDateTime types #429

Closed
nesk opened this issue Sep 1, 2024 · 2 comments
Closed

Plus an minus methods on LocalTime and LocalDateTime types #429

nesk opened this issue Sep 1, 2024 · 2 comments

Comments

@nesk
Copy link

nesk commented Sep 1, 2024

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
Copy link
Collaborator

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
Copy link
Author

nesk commented Sep 2, 2024

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

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

@nesk nesk closed this as completed Sep 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants