tyczj
tyczj

Reputation: 73721

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

Upvotes: 4

Views: 128

Answers (2)

deHaar
deHaar

Reputation: 18558

Why ZonedDateTime.now() when you are obviously just interested in epoch millis?

You could use only Instants 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

user8681
user8681

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

Related Questions