Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 365
tyczj Avatar asked Oct 12 '25 16:10

tyczj


1 Answers

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()}")

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!