Get difference of seconds beetween two dateTime

7.5k views Asked by At

How can I calculate the difference in seconds between two dates?

I have this:

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

In this case the time is: now 2017-09-14T09:49:25.316 midnight 2017-09-15T00:00

How i calculate int second = ...?

And the result, in this case, that i want return is 51035

How i can do?

UPGRADE SOLVED

I try this:

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

Now return the difference beetween the date in seconds in integer variable.

Thank all user for response.

3

There are 3 answers

3
Nicola Ambrosetti On BEST ANSWER
int seconds = (int) ChronoUnit.SECONDS.between(now, midnight); 
0
Luciano van der Veekens On

Convert them to seconds since Epoch and compare differences.

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
Mathias G. On

I would do this through epochTime:

ZoneId zoneId = ZoneId.systemDefault();

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

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

and then calculate the difference:

long result = (epochInSecondsMidnight - epochInSecondsNow)