Compute times in Java eg. 1900 1710 = 110 mins

is there any way in java to do that? I want it to compute the times like that. 0950-0900 is 50 mins but 1700-1610 = 50 mins instead of 90, 1900-1710 = 110 instead of 190. thanks :)

Jon Skeet
people
quotationmark

If you've just got integers, and you don't care about validation, you can do it all without touching time parts at all:

public int getMinutesBetween(int time1, int time2) {
    // Extract hours and minutes from compound values, which are base-100,
    // effectively.
    int hours1 = time1 / 100;
    int hours2 = time2 / 100;
    int minutes1 = time1 % 100;
    int minutes2 = time2 % 100;
    // Now we can perform the arithmetic based on 60-minute hours as normal.
    return (hours2 - hours1) * 60 + (minutes2 - minutes1);
}

However, I'd strongly recommend that you use more appropriate representations - these aren't just normal int values... they're effectively "time of day" values, so LocalTime (in either Joda Time or Java 8's java.time) is the most appropriate representation, IMO.

people

See more on this question at Stackoverflow