2017-09-14 278 views
-1

如何計算兩個日期之間的秒差?獲取兩個日期之間的差異秒數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 = ...?

而結果,在這種情況下,我想回報是51035

我該怎麼辦?

升級解決

我試試這個:

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

現在返回秒整型變量beetween日期的差異。

感謝所有用戶的回覆。

+0

這是java的遺憾 –

回答

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

乾淨的解決方案。其實清潔,那麼我的。請注意,需要使用Java 8來使用ChronoUnit類 –

+1

@MathiasGhys'LocalDateTime'已經是Java 8的一部分。 –

+3

'()'之間'返回'long'。如果你想分配一個'int'(在這種情況下是合理的),我建議在投射前進行邊界檢查。 –

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