2017-09-14 1 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

내가 반환 51,035

이다 것인지,이 경우, int second = ...?

그리고 결과를 계산하는 방법

내가 어떻게 할 수 있습니까?

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

이제 정수 변수에 초 단위로 날짜 beetween 차이를 반환 :

업그레이드 내가 이것을 시도

를 해결했다.

모든 사용자에게 답변 해 주셔서 감사합니다.

+0

이 자바 죄송 –

답변

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

클린 솔루션입니다. 사실 더 청소 해주세요. Java 8은 ChronoUnit 클래스를 사용하는 데 필요합니다. –

+1

@MathiasGhys'LocalDateTime'은 이미 Java 8의 일부입니다. –

+3

'between()'은'long'을 반환합니다. 'int' (이 경우 합리적인)에 할당하고 싶다면 캐스팅하기 전에 bounds check를 권합니다. –

0

Epoch 이후로 초로 변환하고 차이점을 비교하십시오.

ZoneId zoneId = ZoneId.systemDefault(); 

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

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

를 다음의 차이 계산 :

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을 통해이 작업을 수행 할 것

long result = (epochInSecondsMidnight - epochInSecondsNow) 
관련 문제