kotlinx-datetime icon indicating copy to clipboard operation
kotlinx-datetime copied to clipboard

Inherit the specified TimeZone when converting between Instant and LocalDateTime using toInstant and toLocalDateTime?

Open ArcherEmiya05 opened this issue 1 year ago • 1 comments

I am trying to convert the following Java 8 Desugar DateTime.

        val currentDate = LocalDateTime.now().atOffset(ZoneOffset.UTC)

        val currentDateInMilli = currentDate.toInstant().toEpochMilli()
        val oldestDateInMilli = currentDate.minusYears(currentDate.year - 2009L).toInstant().toEpochMilli()
        val previousMonthInMilli = currentDate.minusMonths(1).toInstant().toEpochMilli()

I ended up with this

        val now = Clock.System.now()

        val currentDate = now.toLocalDateTime(TimeZone.UTC)

        val currentDateInMilli = currentDate.toInstant(TimeZone.UTC).toEpochMilliseconds()
        val oldestDateInMilli = now.minus(currentDate.year - 2009L, DateTimeUnit.YEAR, TimeZone.UTC).toEpochMilliseconds()
        val previousMonthInMilli = now.minus(1, DateTimeUnit.MONTH, TimeZone.UTC).toEpochMilliseconds()

What I noticed is the repeated setting of TimeZone, would it be good if there will be a default value on it by reusing the TimeZone used on its origin?

ArcherEmiya05 avatar Jul 15 '24 23:07 ArcherEmiya05

I had the same question, but as I understand LocalDateTime do not contain information about the timezone, so it cannot be reused

Kostyshina avatar Feb 28 '25 12:02 Kostyshina