Nanda Ardianto
Nanda Ardianto

Reputation: 367

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 :)

Upvotes: 2

Views: 113

Answers (3)

Puce
Puce

Reputation: 38142

Have a look at Duration (part of the new Date & Time API introduced in Java SE 8).

Eg. (untested):

long minutes = Duration.between(toLocalTime(1710), toLocalTime(1900)).toMinutes();

private LocalTime toLocalTime(int time){
  return LocalTime.of(time / 100, time % 100);
}

Upvotes: 6

Jon Skeet
Jon Skeet

Reputation: 1502016

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.

Upvotes: 2

PhilippS
PhilippS

Reputation: 3385

You can use the new Java Date API from Java 8.

LocalTime start = LocalTime.parse("19:00");
LocalTime end = LocalTime.parse("17:10");
Duration elapsed = Duration.between(start, end);
System.out.println(elapsed.toMinutes());

This will output: -110 and 110 if you switch start and end.

Upvotes: 2

Related Questions