我有一个春季引导后端,我想每天早上9点在UTC+1上发布新闻。
我想要一个java.time.Instant:
取决于如果我们上午9点,我如何才能可靠地为我的所有客户?
发布于 2020-03-17 13:47:52
您可以这样使用OffsetDateTime:
LocalTime targetTime = LocalTime.of(9, 0);
OffsetDateTime dateTime = OffsetDateTime.now(ZoneOffset.ofHours(1));
if (dateTime.toLocalTime().compareTo(targetTime) >= 0)
dateTime = dateTime.plusDays(1);
Instant instant = dateTime.with(targetTime).toInstant();
System.out.println(instant);产出(在2020-03-17T14:47+01:00执行)
2020-03-18T08:00:00Z如果上午9点应该保持不变,则将>=更改为>。
发布于 2020-03-17 13:42:08
澄清了一些误解后,对答案进行了调整,以使用客户端的默认时区并返回一个Instant。
这意味着,您可以在系统区域中使用ZonedDateTime,查看以下方法及其注释:
public static Instant determineNextNewsRelease() {
// get the current time using the default time zone of the client
ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
// get 9 AM using the same day/date
ZonedDateTime nineAM = now.with(LocalTime.of(9, 0));
// and check if now is before nineAM
if (now.isBefore(nineAM)) {
return nineAM.toInstant();
} else {
return nineAM.plusDays(1).toInstant();
}
}使用如下方法:
public static void main(String[] args) {
Instant nextNewsRelease = determineNextNewsRelease();
// and print the result
System.out.println("Next news will be released at "
+ nextNewsRelease.toEpochMilli() + " ("
+ ZonedDateTime.ofInstant(nextNewsRelease, ZoneId.systemDefault())
+ ")");
}打印的结果是
Next news will be released at 1584518400000 (2020-03-18T09:00+01:00[Europe/Berlin])试试吧..。
https://stackoverflow.com/questions/60723112
复制相似问题