Reputation: 73721
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
Upvotes: 4
Views: 128
Reputation: 18558
Why ZonedDateTime.now()
when you are obviously just interested in epoch millis?
You could use only Instant
s instead:
fun main() {
var now = Instant.now()
var nowPlusOneDay = now.plus(1, ChronoUnit.DAYS)
println("now: ${now.toEpochMilli()}")
println("one day later: ${nowPlusOneDay.toEpochMilli()}")
}
Output (some seconds ago):
now: 1695392676969
one day later: 1695479076969
Upvotes: 1
Reputation:
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()}")
Upvotes: 9