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?
-
1No, there is no way to set the time in an existing `LocalDateTime` object. The object is immutable. As most objects of classes of java.time. – Ole V.V. Oct 29 '21 at 10:20
3 Answers
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
.

- 302,674
- 57
- 556
- 614
-
-
2As the author of JSR-310, I can say that `ldt.with(LocalTime.MIDNIGHT)` is the way that users are expected to do this. – JodaStephen Oct 29 '21 at 12:38
-
@JodaStephen could you briefly explain the thought process behind .with function. As you mentioned, that's the way users are expected to do it rather than various other approached – joseph Oct 29 '21 at 14:15
-
1`with()` replaces one part of the target object with another thing. Here it replaces the time in a `LocalDateTime`, but it could replace the date, or just the year. It is a generally useful, method, and is conceptually high level unlike truncating – JodaStephen Oct 30 '21 at 21:18
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.

- 10,307
- 4
- 35
- 40
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()

- 12,568
- 8
- 34
- 67