BokBok BokBok - 1 month ago 8
Java Question

Calculate time difference between two times represented as longs

I am trying to calculate the difference between two times, which are represented as longs in the Format HHmm 24 hour time. E.g 4:30pm is represented by the long 0430.

I am happy for the difference to be in minutes.

Is there a simple calculation that can be done to achieve this? I am aware of Java's Date class, however I want to avoid having to store dummy date information just for a calculation on time.



Putting aside the fact that this is a really, really bad way to store times, the easiest way to do this is to convert the HHMM time to minutes since the start of the day:

long strangeTimeFormatToMinutes(long time) {
  long minutes = time % 100;
  long hours   = time / 100;
  return minutes + 60 * hours;

Then just use plain old subtraction to get the difference.

You may also want to add validation that minutes and hours are in the ranges you expect, i.e. 0-59 and 0-23.