Reputation: 81
I just want to calculate time difference in minutes, hopefully there is already a class which does it correctly. So the values which I get from the website are only Hours and Minutes (for instance: event starts at: 20:30 and ends at 03:30).
When I use 'Duration.between' I get incorrect values - it is happening when the first value is greater than second or second is past midnight. I think I would be able to do this with 'ifs' and 'elses' but I am sure that there is already a class or a method which would solve the issue in more elegant way, but I can't find it. Here is my code: it works only when the second value is greater than first:
LocalTime eventStarts = LocalTime.now();
LocalTime eventEnds = LocalTime.now();
eventStarts = eventStarts.withHour(22).withMinute(00);
eventEnds = eventEnds.withHour(03).withMinute(00);
Duration durationBetweenEvents = Duration.between(eventStarts, eventEnds);
System.out.println(durationBetweenEvents.toMinutes());
in this case i get '-1140'
Upvotes: 1
Views: 64
Reputation: 340230
LocalTime
has no notion of dates or days. So it is limited to a single generic 24-hour day. Going from an evening time to a morning time is viewed as going backwards in time, not wrapping around to another day as no days exist.
To know the duration of an actual event you need dates and time zone.
Getting the current date requires a time zone. For any given moment, the date varies around the globe by zone.
Once you have dates, apply a ZoneId
to get ZonedDateTime
objects. From there you can get a Duration
that takes into account anomalies such as Daylight Saving Time (DST).
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
LocalDate tomorrow = today.plusDays( 1 );
ZonedDateTime zdtStart =
ZonedDateTime.of( today , LocalTime.parse( "20:30" ) , z ) ;
ZonedDateTime zdtStop =
ZonedDateTime.of( tomorrow , LocalTime.parse( "03:30" ) , z ) ;
Duration d = Duration.between( zdtStart , zdtStop ) ;
long totalMinutes = d.toMinutes() ;
zdtStart.toString(): 2017-04-13T20:30-04:00[America/Montreal]
zdtStop.toString(): 2017-04-14T03:30-04:00[America/Montreal]
d.toString(): PT7H
totalMinutes: 420
See this code run live at IdeOne.com.
Upvotes: 1
Reputation: 79875
Just add the following to your code.
if (durationBetweenEvents.isNegative()) {
durationBetweenEvents = durationBetweenEvents.plusDays(1);
}
You have to be a little careful with daylight savings. Your calculation can be an hour out, if daylight savings time starts or ends between the events. But without knowing date or timezone information, there's no way to deal with that.
Upvotes: 1