Evan
Evan

Reputation: 880

Finding the difference between two times in 12 hour AM/PM format

One part of my program needs to find the smallest difference between two times. For example:

Time 1: 11 AM

Time 2: 1 PM

The difference should be 2 hours, not 22 hours (it shouldn't matter what order the times are given in). For now, assume that the two times will always be different. I have two strings and two ints that are used to store the times:

int startTime = 11;

String startTimeType = "AM";

int endTime = 1;

String endTimeType = "PM";

I tried hardcoding it by taking each possible combination of AM/PM:

e.g. In combination 1 (AM/AM), the code would be:

int timeDifference = 0;

if (startTimeType.equals("PM")
   startTime += 12;

if (endTimeType.equals("PM")
   endTime += 12;

if ((startTimeType.equals("AM") && endTimeType.equals("AM"))
{     
      timeDifference = Math.abs(startTime - endTime);
}

Is there any way to do this without hardcoding?

Upvotes: 1

Views: 3504

Answers (2)

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31269

You can use a time library. Either JodaTime or the built-in java.time API if you have jdk1.8+:

import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

public class TimeDiff {
    public static void main(String[] args) {
        DateTimeFormatter format = DateTimeFormatter
                .ofLocalizedTime(FormatStyle.SHORT);
        LocalTime time1 = LocalTime.parse("11:00 AM", format);
        LocalTime time2 = LocalTime.parse("01:00 PM", format);
        Duration duration = Duration.between(time1, time2);
        System.out.println(Math.abs(duration.getSeconds() / 3600));
    }
}

Upvotes: 2

Everv0id
Everv0id

Reputation: 1980

Maybe if (difference > 12) difference = 24 - difference?

Upvotes: 2

Related Questions