Question

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

Était-ce utile?

La solution 2

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"));
    }
}

Autres conseils

The right way to work with times and dates is to use a time/date utility library. Attempting to do the math manually yourself is a good recipe to shoot yourself in the foot.

Your two best choices are Joda-Time, if you aren't running Java 8, or the java.time package if you are.

I'll give you an example with Joda-Time, since I'm not running Java 8 sadly, but I'll update this answer with a Java 8 example as well when I have a chance. They're functionally very similar (java.time was largely based on Joda-Time).

LocalTime nineTwentyFive = new LocalTime(9, 25);
LocalTime tenTen = new LocalTime(10, 10);
LocalTime tenFifteen = new LocalTime(10, 15);
LocalTime tenTwentyFive = new LocalTime(10, 25);

System.out.println(Minutes.minutesBetween(tenFifteen, tenTwentyFive).getMinutes());
System.out.println(Minutes.minutesBetween(nineTwentyFive, tenTen).getMinutes());
10
45

Both libraries are highly tested and popular, meaning you can trust them to do the right thing out of the box, even in edge cases you don't anticipate. Don't re-implement this behavior yourself.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top