Hey everyone, is there equivalent of `truncatedTo(...
# kotlinx-datetime
s
Hey everyone, is there equivalent of
truncatedTo(ChronoUnit.SECONDS)
that is present in Java local datetime in KotlinX ?
d
Currently, there isn't, we didn't see any significant demand. You're welcome to share your use case: https://github.com/Kotlin/kotlinx-datetime/issues/225!
s
Hey @Dmitry Khalanskiy [JB]! thanks for your reply I'm using Kotlinx to in an 'Interview scheduling system' for which I'd like to set all the meeting share at 0 SECONDS. Hence my need to use
truncateTo()
d
Where does the data come from that doesn't already have seconds set to zero?
s
It's defined by user, from UI input
d
Why does the UI input allow times with non-zero seconds if they are ultimately discarded?
s
that's beyond my team scope to control, it 's like a common UI component that is used on other teams.
d
Got it, thanks!
s
what do you think about complexity of adding this? Is it sth that I can contribute?
d
The complexity of this is tiny, here's the whole thing:
Copy code
public fun LocalTime.truncateTo(unit: DateTimeUnit.TimeBased): LocalTime =
    LocalTime.fromNanosecondOfDay(toNanosecondOfDay().let { it - it % unit.nanoseconds })

public fun LocalDateTime.truncateTo(unit: DateTimeUnit.TimeBased): LocalDateTime =
    LocalDateTime(date, time.truncateTo(unit))
Here are some tests to make sure it works:
Copy code
@Test
    fun testTruncation() {
        val localTime = LocalTime(1, 2, 3, 456789123)
        assertEquals(LocalTime(1, 2, 3, 456789123), localTime.truncateTo(DateTimeUnit.NANOSECOND))
        assertEquals(LocalTime(1, 2, 3, 456789000), localTime.truncateTo(DateTimeUnit.MICROSECOND))
        assertEquals(LocalTime(1, 2, 3, 456000000), localTime.truncateTo(DateTimeUnit.MILLISECOND))
        assertEquals(LocalTime(1, 2, 3, 0), localTime.truncateTo(DateTimeUnit.SECOND))
        assertEquals(LocalTime(1, 2, 0, 0), localTime.truncateTo(DateTimeUnit.MINUTE))
        assertEquals(LocalTime(1, 0, 0, 0), localTime.truncateTo(DateTimeUnit.HOUR))
    }
The complexity is in making this consistent with the more general request of temporal adjusters: https://github.com/Kotlin/kotlinx-datetime/issues/235 This requires careful considerations and thorough design.
s
perfect! I guess that works for my requirements
Although I would be happy if I can contribute on this topic if it's needed
224 Views