Search code examples
javastringcompiler-errorsinttypeconverter

Java Hour to Minutes Simple conversion


I am working on a simple program which given 2 times (1015 and 1025 and 0925 and 1010) will return the time difference in minutes between them.

So

1015 and 1025 -> 10 minutes difference


Solution

  • This simple math formula will give you the answer:

    ((10*60 +10) - (9*60 + 25))
    

    So now all you need to do is:

    1. Split the 4 digits string into 2 group numbers.
    2. Calculate the minutes by Converting the hours into minutes and add them into the minutes new number.
    3. Subtract the bigger number from the smaller one.

    Walla!

    Code example:

    public class goFile {
        public static int SubtractTime(String number1, String number2)
        {
            return Math.abs(ConvertTimeToMinutes(number2) - ConvertTimeToMinutes(number1));
        }
    
        public static int ConvertTimeToMinutes(String number)
        {
            return Integer.parseInt(number.substring(0, 2))*60 + Integer.parseInt(number.substring(2, 4));
        }
    
        public static void main(String[] args) {
            System.out.println(SubtractTime("0925", "1010"));
            System.out.println(SubtractTime("1015", "1025"));
        }
    }