Java 8 LocalDateTime today at specific hour
Another alternative (specially if you want to change an already existing LocalDateTime
) is to use the with()
method.
It accepts a TemporalAdjuster
as a parameter. And according to javadoc, passing a LocalTime
to this method does exactly what you need:
The classes LocalDate and LocalTime implement TemporalAdjuster, thus this method can be used to change the date, time or offset:
result = localDateTime.with(date);
result = localDateTime.with(time);
So, the code will be:
LocalDateTime todayAt6 = LocalDateTime.now().with(LocalTime.of(6, 0));
LocalDate
has various overloaded atTime
methods, such as this one, which takes two arguments (hour of day and minute):
LocalDateTime todayAt6 = LocalDate.now().atTime(6, 0);
An alternative to LocalDate.now().atTime(6, 0)
is:
import java.time.temporal.ChronoUnit;
LocalDateTime.now().truncatedTo(ChronoUnit.DAYS).withHour(6);