Java 8 LocalDateTime today at specific hour
Asked Answered
S

5

55

Is there a nicer/easier way of constructing LocalDateTime object representing today at 6 AM than this?

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

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

Swabber answered 28/4, 2016 at 12:23 Comment(0)
P
75

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);
Piercing answered 28/4, 2016 at 12:31 Comment(0)
D
18

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));
Destination answered 19/6, 2017 at 16:10 Comment(0)
B
8

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

import java.time.temporal.ChronoUnit;

LocalDateTime.now().truncatedTo(ChronoUnit.DAYS).withHour(6);
Byline answered 28/1, 2018 at 15:29 Comment(0)
A
8

That works

LocalDateTime.now().withHour(3).withMinute(0).withSecond(0);
Apocarp answered 4/3, 2019 at 15:23 Comment(0)
T
3

The accepted answer is a good one. 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 used repeatedly, 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);
Tin answered 19/6, 2017 at 8:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.