javakotlinzoneddatetime

Adding days to ZonedDateTime does not change the time


I am trying to get an instance of ZonedDateTime then add 1 day to it then I want to know what the time is in mills at UTC but when I use plusDays the time stays the same and I am not sure why

here is what I am doing

val zdt: ZonedDateTime = ZonedDateTime.now()

println("${zdt.toInstant().toEpochMilli()}")

zdt.plusDays(1)

println("${zdt.toInstant().toEpochMilli()}")

zdt.withHour(0)
zdt.withMinute(0)
zdt.withSecond(0)

println("${zdt.toInstant().toEpochMilli()}")

all print statements print out the same value, what am I missing here?

Here is a link to the code sample

https://pl.kotl.in/QmlXRd-HM


Solution

  • Those methods don't modify the ZonedDateTime instance. They return new ones. The java.time classes use immutable objects.

    To fix your code, update the variable:

    var zdt: ZonedDateTime = ZonedDateTime.now()
    println("${zdt.toInstant().toEpochMilli()}")
    zdt = zdt.plusDays(1)
    println("${zdt.toInstant().toEpochMilli()}")
    zdt = zdt.withHour(0).withMinute(0).withSecond(0)
    println("${zdt.toInstant().toEpochMilli()}")