-1

How do i subtract two times which are in two different dates, say 23:20:45 of 2019/07/24 and 00:10:32 of 2019/07/25. It should return me the difference between those two hours:minutes:seconds.

I have to note the duration of people which log into the system at night, but as the date changes it's a bit difficult to do so I need some code in java which will return me the exact time in hours:minutes:seconds.

Omkar Khandekar
  • 55
  • 2
  • 14

2 Answers2

1

Your logs should be recording the users’ activity using a moment in UTC, written as text in standard ISO 8601 format. The Z on the end means an offset from UTC of zero hours-minutes-seconds, and is pronounced “Zulu”. Example: 2019-07-24T23:20:45Z.

The Instant class represented a moment in UTC.

Instant instant = Instant.now() ;
String output = instant.now();

Parse.

Instant start = Instant.parse( "2019-07-24T23:20:45Z" ) ;

Calculate elapsed time.

Duration d = Duration.between( start , stop ) ;

Report the duration in standard ISO 8601 text, PnYnMnDTnHnMnS.

String output = d.toString() ;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
1
LocalDateTime from = LocalDateTime.parse("2019/07/24 23:20:45", formatter);
LocalDateTime to = LocalDateTime.parse("2019/07/25 00:10:32", formatter);
System.out.println(Duration.between(to.toLocalTime(),from.toLocalTime()).getSeconds());

So, since the requrements recently changed and it is now about the total duration between to moments in time, and not the duration between the time-part only, omitting the date-part, the whole thing gets simpler, then it it's just

System.out.println(Duration.between(to,from).getSeconds());

... and a duplicate question ...

Curiosa Globunznik
  • 3,129
  • 1
  • 16
  • 24