0

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?

AlexElin
  • 1,044
  • 14
  • 23
joseph
  • 147
  • 7
  • 1
    No, 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 Answers3

4

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):

  1. atMidnight = ldt.with(LocalTime.MIDNIGHT) (preferred method)
  2. atMidnight = ldt.truncatedTo(ChronoUnit.DAYS)
  3. atMidnight = ldt.toLocalDate().atStartOfDay()

Lastly, if you really meant "with no time", then you can simply convert the LocalDateTime to a LocalDate using toLocalDate.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • A very full answer. Thanks. – Ole V.V. Oct 29 '21 at 10:21
  • 2
    As 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
1

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.

tgdavies
  • 10,307
  • 4
  • 35
  • 40
0

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()
dan1st
  • 12,568
  • 8
  • 34
  • 67