Java 8 LocalDateTime today at a specific time

Is there a better / simpler way to build a LocalDateTime object presenting today at 6 a.m.?

 LocalDateTime todayAt6 = LocalDateTime.now().withHour(6).withMinute(0).withSecond(0).withNano(0); 

Somehow I don’t like to communicate with minutes / seconds / nano when all I want to say is now().withHours() .

+7
java java-8 java-time
source share
4 answers

LocalDate has various atTime methods atTime , such as this , which takes two arguments (hour of day and minute):

 LocalDateTime todayAt6 = LocalDate.now().atTime(6, 0); 
+15
source share

The accepted answer is good. You can also create your own clock to do this:

 Clock clock = Clock.tick(Clock.systemDefaultZone(), Duration.ofHours(1)); LocalDateTime dt = LocalDateTime.now(clock); 

This can be a useful option if it is reused, because the clock can be stored in a static variable:

 public static final Clock CLOCK = Clock.tick(Clock.systemDefaultZone(), Duration.ofHours(1)); LocalDateTime dt = LocalDateTime.now(CLOCK); 
+3
source share

Another alternative (especially if you want to modify an existing LocalDateTime ) is to use the with() method.

It takes a TemporalAdjuster parameter as a parameter. And according to javadoc , passing LocalTime to this method does exactly what you need:

The LocalDate and LocalTime classes implement TemporalAdjuster, so 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)); 
+1
source share

An alternative to LocalDate.now().atTime(6, 0) is:

 import java.time.temporal.ChronoUnit; LocalDateTime.now().truncatedTo(ChronoUnit.DAYS).withHour(6); 
0
source share

All Articles