如何根据当前秒数获取第二天的第一秒?

How to get first seconds of the next day based on current seconds?

我必须将 UTC 中的秒数转换为天,然后添加一天的间隔和 UTC 中的 return 秒。

这是我的:

选项 #1

public static final long nextDayStartSec(long epochSecondsInUTC) {
    return (epochSecondsInUTC / TimeUnit.DAYS.toSeconds(1) + 1) * TimeUnit.DAYS.toSeconds(1);
}

但根据Wikipedia,并不是所有的日子都包含 86400 秒:

Modern Unix time is based on UTC, which counts time using SI seconds, and breaks up the span of time into days almost always 86400 seconds long, but due to leap seconds occasionally 86401 seconds.

选项#2

public static final long nextDayStartSec(long epochSecondsInUTC) {
    return DateUtils.addMilliseconds(DateUtils.round(new Date(TimeUnit.SECONDS.toMillis(epochSecondsInUTC)), Calendar.DATE), -1)
            .toInstant().atZone(systemDefault()).toLocalDateTime().toEpochSecond(ZoneOffset.UTC);
}

但它使用了广泛的库(包括 Apache Commons)并且难以阅读。

有没有我漏掉的简单的东西?

如果你使用 Java 8,新的时间 API 允许你这样写(它给给定的时刻增加一天):

public static final long nextDayStartSec(long epochSecondsInUTC) {
  OffsetDateTime odt = Instant.ofEpochSecond(epochSecondsInUTC).atOffset(ZoneOffset.UTC);
  return odt.plusDays(1).toEpochSecond();
}

如果你想得到第二天开始的时刻,它可能是这样的:

public static final long nextDayStartSec(long epochSecondsInUTC) {
  OffsetDateTime odt = Instant.ofEpochSecond(epochSecondsInUTC).atOffset(ZoneOffset.UTC);
  return odt.toLocalDate().plusDays(1).atStartOfDay(ZoneOffset.UTC).toEpochSecond();
}