获取两个dateTime之间的秒数差异

时间:2017-09-14 07:54:51

标签: java localdate

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

我有这个:

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

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

感谢所有用户的回复。

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

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

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

答案 2 :(得分: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)