Java获得即时第二天午夜时间



现在我有了代码,它将24小时添加到当前时间中。我需要换一下,第二天的时间是午夜。在我的情况下,我需要输出:2021-11-30T00:00:00.815109800Z

ZonedDateTime Date = ZonedDateTime.now(Database.ZONE_ID);

Date.plusSeconds(86400)).toInstant()电流输出为2021-11-30T11:05:58.815109800Z

我需要今天结束/明天开始00:00:00。我该怎么做?

好吧,如果你想在午夜,那么你可以使用truncatedTo:

ZonedDateTime date = ZonedDateTime.parse("2021-11-29T11:31:15.815109800Z")
.plusDays(1)
.truncatedTo(ChronoUnit.DAYS);

truncatedTo的效果是,它将所有小于所提供参数的字段设置为零。在我们的案例中,我们提供了,因此小时、分钟、秒和秒分数设置为0。

但这也会将秒的分数设置为零。根据这个问题判断,你想保留秒的分数。不知道你为什么要这样,但嘿,这是你的问题。

如果你真的想保留秒的分数,那么你必须将小时、分钟和秒设置为零:

ZonedDateTime date = ZonedDateTime.parse("2021-11-29T11:31:15.815109800Z")
.plusDays(1)
.withHour​(0)
.withMinute(0)
.withSecond(0);
// Or reset hour, minute and seconds at once:
//  .with(ChronoField.SECOND_OF_DAY, 0)

现在,如果您经常使用这种转换,您也可以编写一个TemporalAdjuster,然后调用ZonedDateTime::with(TemporalAdjuster)方法。例如:

TemporalAdjuster nextDayWithFractionOfSecondAdjuster = temporal -> temporal
.plus(1, ChronoUnit.DAYS)
.with(ChronoField.SECOND_OF_DAY, 0);
ZonedDateTime date = ZonedDateTime.parse("2021-11-29T11:05:58.815109800Z")
.with(nextDayWithFractionOfSecondAdjuster)

最新更新