Modifiying time in LocalTimeDate object

1.5k views Asked by At

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?

3

There are 3 answers

4
Joachim Sauer On BEST 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):

  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.

0
tgdavies 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
dan1st might be happy again 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()