Reputation: 880
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:
startTimeType = "AM", endTimeType = "AM";
startTimeType = "AM", endTimeType = "PM";
startTimeType = "PM", endTimeType = "AM";
startTimeType = "PM", endTimeType = "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
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