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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 18:48:54  来源:igfitidea点击:

Java 8 LocalDateTime today at specific hour

javajava-8java-time

提问by JanM

Is there a nicer/easier way of constructing LocalDateTimeobject 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

LocalDatehas various overloaded atTimemethods, such as this one, which takes two arguments (hour of day and minute):

LocalDate有各种重载atTime方法,例如this,它需要两个参数(一天中的小时和分钟):

LocalDateTime todayAt6 = LocalDate.now().atTime(6, 0);

回答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 TemporalAdjusteras a parameter. And according to javadoc, passing a LocalTimeto 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);