Time Difference (HH:MM:SS)
Problem
Two times of the same day in the form HH:MM:SS are given: a start and an end. Print how much time passes from the start to the end as HH:MM:SS. If the end is earlier than the start, the end is on the next day. If both times are equal, the difference is 00:00:00.
Constraints
- valid HH:MM:SS times
Examples
Input
10:15:30 12:00:00
Output
01:44:30
Input
23:00:00 01:30:15
Output
02:30:15
Solutions
Convert both times to seconds since midnight, subtract, and fix the sign with one remainder operation. In Java and JavaScript the % of a negative number is negative, so we add 86400 before the second remainder.
/*
* Problem : Time difference.
* Input : Two times.
* Output : The difference.
* Approach: Seconds since midnight.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// Convert a time HH:MM:SS to the number of seconds since midnight.
static long toSeconds(String time) {
String[] part = time.split(":");
return Long.parseLong(part[0]) * 3600 + Long.parseLong(part[1]) * 60 + Long.parseLong(part[2]);
}
// This method solves the task. It receives the input and returns the answer.
static String solve(String a, String b) {
// Step 1: Work with seconds since midnight. This turns time arithmetic into simple number arithmetic.
long difference = toSeconds(b) - toSeconds(a);
// Step 2: If the end is earlier, add one day. We also use the remainder, so equal times give 0.
difference = ((difference % 86400) + 86400) % 86400;
// Step 3: Convert the seconds back to hours, minutes and seconds with two digits each.
return String.format("%02d:%02d:%02d", difference / 3600, difference % 3600 / 60, difference % 60);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = scanner.next();
String b = scanner.next();
System.out.println(solve(a, b));
}
}
Hints (1)
- Why add 86400 before the second remainder?