Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class TimeDifference {
- // Accept user input for two integers expressing time in an HHMMSS format,
- // calculates the difference between the two timestamps, and returns an
- // integer also in a HHMMSS format
- public static void main(String[] args) {
- // Create a Scanner object
- Scanner input = new Scanner(System.in);
- // Prompt the user for and store the first timestamp
- System.out.print("Please enter the first timestamp (HHMMSS): ");
- int time1 = input.nextInt();
- // Repeat the above process for the second timestamp
- System.out.print("Please enter the second timestamp (HHMMSS): ");
- int time2 = input.nextInt();
- // Define constants for the number of seconds in a minute and hour
- final int SECONDS_IN_MINUTE = 60;
- final int SECONDS_IN_HOUR = 3600;
- // Seperate timestamps into their composite parts and convert to seconds
- // Conversion into seconds for the first timestamp
- int seconds1 = time1 % 100;
- int minutesInSeconds1 = ((time1 % 10000) / 100) * SECONDS_IN_MINUTE;
- int hoursInSeconds1 = (time1 / 10000) * SECONDS_IN_HOUR;
- int timestampInSeconds1 = hoursInSeconds1 + minutesInSeconds1 + seconds1;
- // Conversion into seconds for the second timestamp
- int seconds2 = time2 % 100;
- int minutesInSeconds2 = ((time2 % 10000) / 100) * SECONDS_IN_MINUTE;
- int hoursInSeconds2 = (time2 / 10000) * SECONDS_IN_HOUR;
- int timestampInSeconds2 = hoursInSeconds2 + minutesInSeconds2 + seconds2;
- // Calculate the difference between the two converted timestamps
- int timestampDifference = timestampInSeconds1 - timestampInSeconds2;
- // Convert difference in seconds back into the appropriate units
- int hoursDifference = timestampDifference / SECONDS_IN_HOUR;
- int minutesDifference = (timestampDifference % SECONDS_IN_HOUR) /
- SECONDS_IN_MINUTE;
- int secondsDifference = (timestampDifference % SECONDS_IN_HOUR) %
- SECONDS_IN_MINUTE;
- // Construct the final output as an integer
- int finalOutput = (hoursDifference * 10000) + (minutesDifference * 100) +
- secondsDifference;
- // Return the final output to the user
- System.out.println("The difference between the two timestamps is: " +
- finalOutput);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement