0

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.

peppe71-19
  • 212
  • 1
  • 5
  • 20

3 Answers3

8
int seconds = (int) ChronoUnit.SECONDS.between(now, midnight); 
Nicola Ambrosetti
  • 2,567
  • 3
  • 22
  • 38
0

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);
Luciano van der Veekens
  • 6,307
  • 4
  • 26
  • 30
0

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)
Mathias G.
  • 4,875
  • 3
  • 39
  • 60