Java 8 LocalDateTime 今天在特定时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36914596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 LocalDateTime today at specific hour
提问by JanM
Is there a nicer/easier way of constructing LocalDateTime
object representing today at 6 AM than this?
有没有比这更好/更简单的方法来构造LocalDateTime
今天早上 6 点表示的对象?
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()
.
不知何故,当我只想说now().withHours()
.
采纳答案by assylias
回答by JodaStephen
The accepted answer is a good one. You can also create your own clockto 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);
回答by JodaStephen
Another alternative (specially if you want to change an already existing LocalDateTime
) is to use the with()
method.
另一种选择(特别是如果您想更改已经存在的LocalDateTime
)是使用with()
方法。
It accepts a TemporalAdjuster
as a parameter. And according to javadoc, passing a LocalTime
to this method does exactly what you need:
它接受 aTemporalAdjuster
作为参数。根据javadoc,将 a 传递LocalTime
给此方法完全符合您的需要:
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);
LocalDate 和 LocalTime 类实现了 TemporalAdjuster,因此该方法可用于更改日期、时间或偏移量:
结果 = localDateTime.with(date);
结果 = localDateTime.with(time);
So, the code will be:
所以,代码将是:
LocalDateTime todayAt6 = LocalDateTime.now().with(LocalTime.of(6, 0));
回答by flurdy
An alternative to LocalDate.now().atTime(6, 0)
is:
一个替代方案LocalDate.now().atTime(6, 0)
是:
import java.time.temporal.ChronoUnit;
LocalDateTime.now().truncatedTo(ChronoUnit.DAYS).withHour(6);
回答by Bruno Lee
That works
那个有效
LocalDateTime.now().withHour(3).withMinute(0).withSecond(0);