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?
Modifiying time in LocalTimeDate object
1.5k Views Asked by joseph At
3
There are 3 best solutions below
0
On
If you look at LocalDateTime you'll see:
/**
* The date part.
*/
private final LocalDate date;
/**
* The time part.
*/
private final LocalTime time;
So LocalDateTime is immutable. This is good because it means that you can pass an instance to other code without worrying that it might get modified, and simplifies access from multiple threads.
I does mean that you will need to create a new instance to modify the time.
0
On
LocalDateTime is immutable, meaning you cannot change a LocalDateTime object (only create new objects). If you use modifying operations, another LocalDateTime object is created.
You could obviously create another object manually but you can also get a LocalDate-object using .toLocalDate and get a LocalDateTime-object again using .atStartOfDay:
yourLocalDateTime.toLocalDate().atStartOfDay()
A given
LocalDateTimeobject can not be modified, since those are immutable. But you can get a newLocalDateTimeobject with the desired dates.There are several ways to do this (all assuming
ldtis the input andatMidnightis a variable of typeLocalDateTime):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
LocalDateTimeto aLocalDateusingtoLocalDate.