-1

I have two times in hours and minutes.

time[0]: hour1
time[1]: minutes1
time[2]: hour2
time[3]: minutes2

I've created this formula to calculate the difference in time in minutes:

((time[2] % 12 - time[0] % 12) * 60) + (time[3] - time[1])

I was wondering if there are any edge cases to this. In addition, what is the paradigm you would follow to create this formula (although it is very basic)?

  • Your algorithm is incorrect. What do you get if `hour1` is 9 and `hour2` is 23 (assume `minutes1` and `minutes2` are zero)? – Jim Garrison Apr 23 '17 at 07:04

2 Answers2

0

You could express your times with the Date class instead, then calculate the difference and then express it in the time unit of your choice.

With this method, you will avoid a lot of tricky cases (difference between two times on two different days, time change, etc.).

I recommend you the reading of this post and this post but there are many answers to this same exact question on StackOverflow ;)

Note: before using Date, have a look to this excellent post: What's wrong with Java Date & Time API?

Community
  • 1
  • 1
Antoine
  • 1,393
  • 4
  • 20
  • 26
0

Your code assumes days are 24 hours long. Not all days are 24-hours long. Anomalies such as Daylight Saving Time (DST) mean days vary in length.

Also, we have classes already built for this. No need to roll your own. The LocalTime class represents a time-of-day without a date and without a time zone. A Duration represents a span of time not attached to the timeline.

LocalTime start = LocalTime.of( 8 , 0 ) ;
LocalTime stop = LocalTime.of( 14 , 0 ) ;

Duration d = Duration.between( start , stop );
long minutes = d.toMinutes() ;  // Entire duration as a total number of minutes. 

That code too pretends that days are 24 hours long.

For realistic spans of time, use the ZonedDateTime class to include a date and time zone along with your time-of-day.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154