Advertisement
Guest User

HerpDeDerp

a guest
Sep 15th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.28 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class TimeDifference {
  4.   // Accept user input for two integers expressing time in an HHMMSS format,
  5.   // calculates the difference between the two timestamps, and returns an
  6.   // integer also in a HHMMSS format
  7.   public static void main(String[] args) {
  8.     // Create a Scanner object
  9.     Scanner input = new Scanner(System.in);
  10.  
  11.     // Prompt the user for and store the first timestamp
  12.     System.out.print("Please enter the first timestamp (HHMMSS): ");
  13.     int time1 = input.nextInt();
  14.  
  15.     // Repeat the above process for the second timestamp
  16.     System.out.print("Please enter the second timestamp (HHMMSS): ");
  17.     int time2 = input.nextInt();
  18.  
  19.     // Define constants for the number of seconds in a minute and hour
  20.     final int SECONDS_IN_MINUTE = 60;
  21.     final int SECONDS_IN_HOUR = 3600;
  22.  
  23.     // Seperate timestamps into their composite parts and convert to seconds
  24.     // Conversion into seconds for the first timestamp
  25.     int seconds1 = time1 % 100;
  26.     int minutesInSeconds1 = ((time1 % 10000) / 100) * SECONDS_IN_MINUTE;
  27.     int hoursInSeconds1 = (time1 / 10000) * SECONDS_IN_HOUR;
  28.     int timestampInSeconds1 = hoursInSeconds1 + minutesInSeconds1 + seconds1;
  29.  
  30.     // Conversion into seconds for the second timestamp
  31.     int seconds2 = time2 % 100;
  32.     int minutesInSeconds2 = ((time2 % 10000) / 100) * SECONDS_IN_MINUTE;
  33.     int hoursInSeconds2 = (time2 / 10000) * SECONDS_IN_HOUR;
  34.     int timestampInSeconds2 = hoursInSeconds2 + minutesInSeconds2 + seconds2;
  35.  
  36.     // Calculate the difference between the two converted timestamps
  37.     int timestampDifference = timestampInSeconds1 - timestampInSeconds2;
  38.  
  39.     // Convert difference in seconds back into the appropriate units
  40.     int hoursDifference = timestampDifference / SECONDS_IN_HOUR;
  41.     int minutesDifference = (timestampDifference % SECONDS_IN_HOUR) /
  42.         SECONDS_IN_MINUTE;
  43.     int secondsDifference = (timestampDifference % SECONDS_IN_HOUR) %
  44.         SECONDS_IN_MINUTE;
  45.  
  46.     // Construct the final output as an integer
  47.     int finalOutput = (hoursDifference * 10000) + (minutesDifference * 100) +
  48.         secondsDifference;
  49.  
  50.     // Return the final output to the user
  51.     System.out.println("The difference between the two timestamps is: " +
  52.         finalOutput);
  53.   }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement