KrissyMichaelsson KrissyMichaelsson - 3 months ago 9
Java Question

How do I get the military time difference to read correctly?

I am trying to write a program in which the console tells a person the difference between two times WITHOUT IF STATEMENTS, in "military time" or 24 hr time. So far, I have:

import java.util.Scanner;

public class MilTimeDiff {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first time: ");
String time1 = s.next();
System.out.print("Enter the second time: ");
String time2 = s.next();
String tm1 = String.format("%02d", Integer.parseInt(time1));
String tm2 = String.format("%02d", Integer.parseInt(time2));
int t1 = Integer.parseInt(tm1);
int t2 = Integer.parseInt(tm2);
int difference = t2 - t1;
while (t1 < t2) {
String tmDif = Integer.toString(difference);
System.out.println("The difference between times is " + tmDif.substring(0, 1) + " hours " +
tmDif.substring(1) + " minutes.");
break;
}
}

}


But I have two issues: one: if I make time one 0800, and time two 1700, it gives me the correct 9 hours. But if the difference is 10 hours or more, it gives 1 hour and a lot of minutes. I thought using the String.format method would help, but it doesn't do anything.

two: I'm not sure how to approach a situation where time 1 is later than time 2.

Thanks!

Answer

You can try below code which will give Time difference in military format :

public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    System.out.print("Enter the first time: ");
    String time1 = s.next();
    System.out.print("Enter the second time: ");
    String time2 = s.next();
    String tm1 = String.format("%02d", Integer.parseInt(time1));
    String tm2 = String.format("%02d", Integer.parseInt(time2));

    String hrs1 = time1.substring(0, 2);
    String min1 = time1.substring(2, 4);
    String hrs2 = time2.substring(0, 2);
    String min2 = time2.substring(2, 4);

    // int difference = t2 - t1;
    if (Integer.parseInt(time1) < Integer.parseInt(time2)) {
        int minDiff = Integer.parseInt(min2) - Integer.parseInt(min1);
        int hrsDiff = Integer.parseInt(hrs2) - Integer.parseInt(hrs1);
        if (minDiff < 0) {
            minDiff += 60;
            hrsDiff--;
        }

        System.out.println("The difference between times is " + hrsDiff + " hours " + minDiff + " minutes.");

    } else {
        int minDiff = Integer.parseInt(min1) - Integer.parseInt(min2);
        int hrsDiff = Integer.parseInt(hrs1) - Integer.parseInt(hrs2);
        if (minDiff < 0) {
            minDiff += 60;
            hrsDiff--;
        }

        System.out.println("The difference between times is " + hrsDiff + " hours " + minDiff + " minutes.");

    }

}