获取两个日期时间之间的秒差

Get difference of seconds beetween two dateTime

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

我有这个:

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 = ...?

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

我该怎么办?

UPGRADE SOLVED

我试试这个:

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

现在 return 整数变量中日期之间的秒数差异。

感谢所有用户的回复。

int seconds = (int) ChronoUnit.SECONDS.between(now, midnight); 

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

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);

我会通过 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)