javajsr310

Modifiying time in LocalTimeDate object


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?


Solution

  • 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.