-1

如何计算两个日期之间的秒差?

我有这个:

LocalDateTime now = LocalDateTime.now(); // current date and time
LocalDateTime midnight = now.toLocalDate().atStartOfDay().plusDays(1); //midnight

在这种情况下,时间是:now 2017-09-14T09:49:25.316 midnight 2017-09-15T00:00

我如何计算int second = ...?

在这种情况下,我想要返回的结果是 51035

我该怎么办?

升级解决

我试试这个:

DateTime now = DateTime.now();
DateTime midnight = now.withTimeAtStartOfDay().plusDays(1);
Seconds seconds = Seconds.secondsBetween(now, midnight);
int diff = seconds.getSeconds();

现在在整数变量中以秒为单位返回日期之间的差异。

感谢所有用户的回复。

4

3 回答 3

5
int seconds = (int) ChronoUnit.SECONDS.between(now, midnight); 
于 2017-09-14T08:02:16.230 回答
0

将它们转换为纪元以来的秒数并比较差异。

LocalDateTime now = LocalDateTime.now();
LocalDateTime tomorrowMidnight = now.toLocalDate().atStartOfDay().plusDays(1);

ZoneId zone = ZoneId.systemDefault();
long nowInSeconds = now.atZone(zone).toEpochSecond();
long tomorrowMidnightInSeconds = tomorrowMidnight.atZone(zone).toEpochSecond();
System.out.println(tomorrowMidnightInSeconds - nowInSeconds);
于 2017-09-14T08:02:58.380 回答
0

我会通过 epochTime 做到这一点:

ZoneId zoneId = ZoneId.systemDefault();

LocalDateTime now = ...;
long epochInSecondsNow = now.atZone(zoneId).toEpochSecond();

LocalDateTime midnight = ...;
long epochInSecondsMidnight = midnight.atZone(zoneId).toEpochSecond();

然后计算差异:

long result = (epochInSecondsMidnight - epochInSecondsNow)
于 2017-09-14T08:04:40.963 回答