0

I'm creating a program to find the time difference between two inputs. The start and the end times are input in 12 hour format such as 9:30am and 11:15am.

I have read the string, use the substring function to extract the string (until the ':') and then converted to integer. The extraction is working perfectly fine.

The problem that I have is with the calculations. e.g. - the time difference between 1:03pm and 12:56pm is 1433 minutes. But my program displays, the difference of 713 minutes.

I have the calculation part of the code up. Any suggestions would be appreciated.

// If-else statements to calculate the total time difference
 if((lower1.indexOf('a') == -1) && (lower2.indexOf('a') == -1) && (intMin1 <= 60) && (intMin2 <= 60)){
    timeDifference = Math.abs((((intHrs1+12)*60)+intMin1) - (((intHrs2+12)*60)+intMin2));
    System.out.println("The time difference is " + timeDifference + " minutes");
} else if((lower1.indexOf('a') != -1) && (lower2.indexOf('a') == -1) && (intMin1 <= 60) && (intMin2 <= 60)) {
    timeDifference = Math.abs((((intHrs2+12)*60)+intMin2) - ((intHrs1*60)+intMin1));         
    System.out.println("The time difference is " + timeDifference + " minutes");
} else if((lower1.indexOf('a') != -1) && (lower2.indexOf('a') != -1) && (intMin1 <= 60) && (intMin2 <= 60)){
    timeDifference = Math.abs(((intHrs2*60)+intMin1) - ((intHrs1*60)+intMin2));
    System.out.println("The time difference is " + timeDifference + " minutes");
} else if((lower1.indexOf('a') == -1) && (lower2.indexOf('a') != -1) && (intMin1 <= 60) && (intMin2 <= 60)){
    timeDifference = Math.abs((((24-(intHrs1+12))*60)+intMin1) - ((intHrs2*60)+intMin2));   
    System.out.println("The time difference is " + timeDifference + " minutes");
} else if(intMin1 >= 60){
     System.out.println("Error: The First time is invalid");
} else {
    System.out.println("Error: The second time is invalid");
}
Sufian
  • 6,405
  • 16
  • 66
  • 120
mandok
  • 17
  • 1
  • 6
  • 6
    http://stackoverflow.com/questions/4927856/how-to-calculate-time-difference-in-java – OldProgrammer Sep 14 '16 at 01:03
  • 2
    In your logic, you are adding 12 hours if it is `pm` instead of `am`, and you have come out a good example that this logic is wrong, which is when `12:56pm`, do you think you should add 12 hours to it ? – Tan Li Hau Sep 14 '16 at 01:05
  • 1
    Sometimes when you try to reinvent the wheel you end up with a square .. – Mark Sep 14 '16 at 01:22
  • Got it figured out. Thanks ! lot. I used a if-else statement and a compareToIgnoreCase method to redo the calculations – mandok Sep 14 '16 at 01:35

2 Answers2

0

DON'T use parseInt and substring for this:

String input1 = "1:03pm".toUpperCase();
String input2 = "12:56pm".toUpperCase();

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mma");
LocalTime time1 = LocalTime.parse(input1, formatter);
LocalTime time2 = LocalTime.parse(input2, formatter);

long durationInMinutes = Duration.between(time1, time2).toMinutes()
if(durationInMinutes < 0) durationInMinutes += 1440; //1440 minutes per day
larsgrefer
  • 2,735
  • 19
  • 36
  • So close, yet..... Result is `-7`, not `1433` – Andreas Sep 14 '16 at 01:32
  • 2
    I have to use parseint and substring. – mandok Sep 14 '16 at 01:35
  • @Andreas Assuming the two times are at the same date, the difference is (-)7 – larsgrefer Sep 14 '16 at 01:37
  • Got it figured out. I used a if-else statement along with compareToIgnoreCase. If the first time as pm and the second time was am. I did (720-(pm time*60)+minutes)+((am time * 60) + minutes + 720) – mandok Sep 14 '16 at 01:39
  • 1
    @mandok why, your code is too complex – larsgrefer Sep 14 '16 at 01:40
  • @larsgrefer Except OP said the desired output is `1433`, so you have to account to day rollover, for the answer to be useful *(ignoring the fact that OP didn't list restrictions in the question)*. – Andreas Sep 14 '16 at 01:40
  • But only if time1 > time2, right? – Andreas Sep 14 '16 at 01:45
  • @larsgrefer The uni has only taught us scanner class. Hence, I do not know how to use the date class. They wanted me to use parseInt and substring to convert the string to integer for calculations. – mandok Sep 14 '16 at 01:53
  • @mandok If they want you to convert string to integer, why don't you? *First* do that conversion, *then* calculate the difference. – Andreas Sep 14 '16 at 01:54
  • I created a variable after comparing two substrings. Then mentioned that if variable > 0 then do one calculation and if variable < 0 then do other calculation. – mandok Sep 14 '16 at 01:55
  • @andreas Yes. Thats exactly what I did. I used substring to extract and parseint to ocnvert and then calculate the difference. – mandok Sep 14 '16 at 22:21
  • @mandok No, first you convert the time into an integer (minute of day), e.g. `"1:03pm"` to `783`, and `"12:56pm"` to `776`, i.e. *"convert string to integer"*. The entire string. – Andreas Sep 14 '16 at 22:39
0

To make your code readable and testable, create helper methods.

public static void main(String[] args) {
    System.out.println(minutesBetween("9:30am", "11:15am"));
    System.out.println(minutesBetween("1:03pm", "12:56pm"));
}
private static int minutesBetween(String time1, String time2) {
    int minutes = toMinuteOfDay(time2) - toMinuteOfDay(time1);
    if (minutes < 0)
        minutes += 1440;
    return minutes;
}
private static int toMinuteOfDay(String time) {
    int colon = time.indexOf(':');
    int hour = Integer.parseInt(time.substring(0, colon));
    int minute = Integer.parseInt(time.substring(colon + 1, colon + 3));
    if (hour == 12)
        hour = 0;
    if (time.indexOf('a') == -1)
        hour += 12;
    return hour * 60 + minute;
}

Output

105
1433
Andreas
  • 154,647
  • 11
  • 152
  • 247