Given a LocalDateTime
object in Java. How do I set the time for this to 00:00:00 ?
One way is to create a new LocalDateTime
object with the same date as this one and set it to 0.
Is there another way to do it?
Advertisement
Answer
A given LocalDateTime
object can not be modified, since those are immutable. But you can get a new LocalDateTime
object with the desired dates.
There are several ways to do this (all assuming ldt
is the input and atMidnight
is a variable of type LocalDateTime
):
atMidnight = ldt.with(LocalTime.MIDNIGHT)
(preferred method)atMidnight = ldt.truncatedTo(ChronoUnit.DAYS)
atMidnight = ldt.toLocalDate().atStartOfDay()
Lastly, if you really meant “with no time”, then you can simply convert the LocalDateTime
to a LocalDate
using toLocalDate
.