Reputation: 305
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
Upvotes: 0
Views: 232
Reputation: 48824
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.
Upvotes: 1
Reputation: 12196
This simple math formula will give you the answer:
((10*60 +10) - (9*60 + 25))
So now all you need to do is:
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"));
}
}
Upvotes: 0