BokBok
BokBok

Reputation: 25

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.

Thanks!

Upvotes: 0

Views: 1150

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 338574

Pad zeros

First convert your integer to a 4-character string, padding with leading zeros.

For example, 430 becomes 0430 and parsed as 04:30. Or, 15 becomes 0015 and parsed as quarter past midnight, 00:15.

String input = String.format( "%04d", yourTimeAsInteger );

LocalDate

The LocalTime class represents a time-of-day value with no date and no time zone.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "HHmm" );

LocalTime ld = LocalTime.parse( input , f ) ;

Upvotes: 0

David Choweller
David Choweller

Reputation: 1050

You mentioned that you didn't want to use the Date class because it required you to use a dummy date. The LocalTime class does not require that.

LocalTime start = LocalTime.of(6,15,30,200); // h, m, s, nanosecs
LocalTime end = LocalTime.of(6,30,30,320);
Duration d = Duration.between(start, end);
System.out.println(d.getSeconds()/60); 

Upvotes: 1

Andy Turner
Andy Turner

Reputation: 140328

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.

Upvotes: 2

Related Questions