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

时间:2015-05-27 12:50:06

标签: java datetime java-time

我必须将UTC中的秒数转换为白天,然后添加一天的间隔并返回UTC的秒数。

这就是我所拥有的:

选项#1

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

但根据Wikipedia

,并非所有日子都包含86400秒
  

现代Unix时间基于UTC,使用SI秒计算时间,   并将时间跨度分解为几乎总是86400秒   很长,但由于闰秒偶尔86401秒。

选项#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)并且难以阅读。

我错过了一些简单的东西吗?

1 个答案:

答案 0 :(得分:2)

如果您使用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();
}