Open In App

Time Difference between given times in HH:MM:SS format

Last Updated : 20 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given 2 times ‘st‘ and ‘et‘ in HH: MM: SS format. The task is to print the time difference between st and et in HH:MM: SS format 

Examples:

Input: st = 13:50:45, et = 14:55:50
Output: 01:05:05
Explanation: The time gap is 1 hour 5 minutes and 5 seconds.

Input: st = 12:00:00, et = 24:00:00
Output: 12:00:00
Explanation: The time gap is of 12 hours.

Approach: The task can be solved by converting both the given times in ‘seconds‘ format & then find the absolute difference between the two. Then convert this absolute difference into HH:MM: SS format
Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
class Solution {
public:
    // Function to find the time difference
    long long int getTimeInSeconds(string str)
    {
 
        vector<int> curr_time;
        istringstream ss(str);
        string token;
 
        while (getline(ss, token, ':')) {
 
            curr_time.push_back(stoi(token));
        }
 
        long long int t = curr_time[0] * 60 * 60
                          + curr_time[1] * 60
                          + curr_time[2];
 
        return t;
    }
 
    // Function to convert seconds back to hh::mm:ss
    // format
    string convertSecToTime(long long int t)
    {
        int hours = t / 3600;
        string hh = hours < 10 ? "0" + to_string(hours)
                               : to_string(hours);
        int min = (t % 3600) / 60;
        string mm = min < 10 ? "0" + to_string(min)
                             : to_string(min);
        int sec = ((t % 3600) % 60);
        string ss = sec < 10 ? "0" + to_string(sec)
                             : to_string(sec);
        string ans = hh + ":" + mm + ":" + ss;
        return ans;
    }
 
    // Function to find the time gap
    string timeGap(string st, string et)
    {
 
        long long int t1 = getTimeInSeconds(st);
        long long int t2 = getTimeInSeconds(et);
 
        long long int time_diff
            = (t1 - t2 < 0) ? t2 - t1 : t1 - t2;
 
        return convertSecToTime(time_diff);
    }
};
 
// Driver Code
int main()
{
 
    string st = "13:50:45", et = "14:55:50";
    Solution ob;
    cout << ob.timeGap(st, et) << "\n";
 
    return 0;
}


Java




// Java program for the above approach
class GFG {
 
    // Function to find the time difference
    static int getTimeInSeconds(String str) {
 
        String[] curr_time = str.split(":");
        int t = Integer.parseInt(curr_time[0]) * 60 * 60 + Integer.parseInt(curr_time[1]) * 60
                + Integer.parseInt(curr_time[2]);
 
        return t;
    }
 
    // Function to convert seconds back to hh::mm:ss
    // format
    static String convertSecToTime(int t) {
        int hours = t / 3600;
        String hh = hours < 10 ? "0" + Integer.toString(hours)
                : Integer.toString(hours);
        int min = (t % 3600) / 60;
        String mm = min < 10 ? "0" + Integer.toString(min)
                : Integer.toString(min);
        int sec = ((t % 3600) % 60);
        String ss = sec < 10 ? "0" + Integer.toString(sec)
                : Integer.toString(sec);
        String ans = hh + ":" + mm + ":" + ss;
        return ans;
    }
 
    // Function to find the time gap
    static String timeGap(String st, String et) {
 
        int t1 = getTimeInSeconds(st);
        int t2 = getTimeInSeconds(et);
 
        int time_diff = (t1 - t2 < 0) ? t2 - t1 : t1 - t2;
 
        return convertSecToTime(time_diff);
    }
 
    // Driver Code
    public static void main(String args[]) {
 
        String st = "13:50:45", et = "14:55:50";
        System.out.println(timeGap(st, et));
    }
}
 
// This code is contributed by saurabh_jaiswal.


Python3




# Python 3 program for the above approach
 
# Function to find the time difference
def getTimeInSeconds(str):
 
    curr_time = str.split(':')
 
    t = (int(curr_time[0]) * 60 * 60
         + int(curr_time[1]) * 60
         + int(curr_time[2]))
 
    return t
 
# Function to convert seconds back to hh::mm:ss
# format
def convertSecToTime(t):
 
    hours = t // 3600
    if hours < 10:
        hh = "0" + str(hours)
    else:
        hh = str(hours)
    min = (t % 3600) // 60
    if min < 10:
        mm = "0" + str(min)
    else:
        mm = str(min)
    sec = ((t % 3600) % 60)
    if sec < 10:
        ss = "0" + str(sec)
    else:
        ss = str(sec)
    ans = hh + ":" + mm + ":" + ss
    return ans
 
# Function to find the time gap
def timeGap(st,  et):
 
    t1 = getTimeInSeconds(st)
    t2 = getTimeInSeconds(et)
 
    if (t1 - t2 < 0):
        time_diff = t2 - t1
    else:
        time_diff = t1 - t2
 
    return convertSecToTime(time_diff)
 
# Driver Code
if __name__ == "__main__":
 
    st = "13:50:45"
    et = "14:55:50"
 
    print(timeGap(st, et))
 
    # This code is contributed by ukasp.


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG {
 
    // Function to find the time difference
    static int getTimeInSeconds(String str) {
 
        String[] curr_time = str.Split(':');
        int t = Int32.Parse(curr_time[0]) * 60 * 60 + Int32.Parse(curr_time[1]) * 60
                + Int32.Parse(curr_time[2]);
 
        return t;
    }
 
    // Function to convert seconds back to hh::mm:ss
    // format
    static String convertSecToTime(int t) {
        int hours = t / 3600;
        String hh = hours < 10 ? "0" + hours.ToString()
                : hours.ToString();
        int min = (t % 3600) / 60;
        String mm = min < 10 ? "0" + min.ToString()
                : min.ToString();
        int sec = ((t % 3600) % 60);
        String ss = sec < 10 ? "0" + sec.ToString()
                : sec.ToString();
        String ans = hh + ":" + mm + ":" + ss;
        return ans;
    }
 
    // Function to find the time gap
    static String timeGap(String st, String et) {
 
        int t1 = getTimeInSeconds(st);
        int t2 = getTimeInSeconds(et);
 
        int time_diff = (t1 - t2 < 0) ? t2 - t1 : t1 - t2;
 
        return convertSecToTime(time_diff);
    }
 
    // Driver Code
    public static void Main(String []args) {
 
        String st = "13:50:45", et = "14:55:50";
        Console.WriteLine(timeGap(st, et));
    }
}
 
// This code is contributed by shikhasingrajput


Javascript




<script>
       // JavaScript code for the above approach
 
       // Function to find the time difference
       function getTimeInSeconds(str) {
 
           let curr_time = [];
 
           curr_time = str.split(':')
           for (let i = 0; i < curr_time.length; i++) {
               curr_time[i] = parseInt(curr_time[i]);
           }
 
           let t = curr_time[0] * 60 * 60
               + curr_time[1] * 60
               + curr_time[2];
 
           return t;
       }
 
       // Function to convert seconds back to hh::mm:ss
       // format
       function convertSecToTime(t) {
           let hours = Math.floor(t / 3600);
           let hh = hours < 10 ? "0" + (hours).toString()
               : (hours).toString();
           let min = Math.floor((t % 3600) / 60);
           let mm = min < 10 ? "0" + (min).toString()
               : (min).toString();
           let sec = ((t % 3600) % 60);
           let ss = sec < 10 ? "0" + (sec).toString()
               : (sec).toString();
           let ans = hh + ":" + mm + ":" + ss;
           return ans;
       }
 
       // Function to find the time gap
       function timeGap(st, et) {
 
           let t1 = getTimeInSeconds(st);
           let t2 = getTimeInSeconds(et);
 
           let time_diff
               = (t1 - t2 < 0) ? t2 - t1 : t1 - t2;
 
           return convertSecToTime(time_diff);
       }
 
       // Driver Code
       let st = "13:50:45", et = "14:55:50";
 
       document.write(timeGap(st, et) + '<br>');
 
 // This code is contributed by Potta Lokesh
   </script>


Output

01:05:05

Time complexity: O(1)
Auxiliary Space: O(1)



Similar Reads

Sum of all numbers formed having 4 atmost X times, 5 atmost Y times and 6 atmost Z times
Given three integers X, Y and Z, the task is to find the sum of all the numbers formed having 4 at most X times, 5 at most Y times, and 6 at most Z times, under mod 10^9+7.Examples: Input: X = 1, Y = 1, Z = 1 Output: 3675 Explanation: 4 + 5 + 6 + 45 + 54 + 56 + 65 + 46 + 64 + 456 + 465 + 546 + 564 + 645 + 654 = 3675 Input: X = 4, Y = 5, Z = 6 Outpu
9 min read
Time difference between expected time and given time
Given the initial clock time h1:m1 and the present clock time h2:m2, denoting hour and minutes in 24-hours clock format. The present clock time h2:m2 may or may not be correct. Also given a variable K which denotes the number of hours passed. The task is to calculate the delay in seconds i.e. time difference between expected time and given time. Ex
5 min read
Maximize time by replacing '_' in a given 24 Hour format time
Given a string S representing a time in 24 hours format, with '_' placed at positions of some digits, the task is to find the maximum time possible by replacing the characters '_' with any digit. Examples: Input: S = “0_:4_”Output: 09:39Explanation: Replacing the characters S[1] and S[4] with '9' modifies the string to "09:49", which is the maximum
7 min read
Count pairs (p, q) such that p occurs in array at least q times and q occurs at least p times
Given an array arr[], the task is to count unordered pairs of positive integers (p, q) such that p occurs in the array at least q times and q occurs at least p times. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 1 (1, 1) is the only valid pair. Input: arr[] = {3, 3, 2, 2, 2} Output: 2 (2, 3) and (2, 2) are the only possible pairs. Approach: The
8 min read
Times required by Simple interest for the Principal to become Y times itself
Given that a certain amount of money becomes T1 times itself in N1 years. The task is to find the number of years i.e. N2 so that the amount becomes T2 times itself at the same rate of simple interest. Examples: Input: T1 = 5, N1 = 7, T2 = 25 Output: 42 Input: T1 = 3, N1 = 5, T2 = 6 Output: 12.5 Approach: Let us consider the 1st Example where T1 =
3 min read
Build a DFA to accept a binary string containing "01" i times and "1" 2j times
Given a binary string str, the task is to build a DFA that accepts given binary string if it contains "01" i times and "1" 2j times, i.e., [Tex]L={(01)^i (1)^{2j} \text{ where }i\geq1\text{ and }j\geq1} [/Tex] Examples: Input: str = "011111" Output: Accepted Explanation: The string follows the language as: (01)1(1)2*2 Input: str = "01111" Output: N
9 min read
Lexicographically Kth-smallest string having 'a' X times and 'b' Y times
Given three non-negative integers, X, Y, and K, the task is to find the Kth smallest lexicographical string having X occurrences of character 'a' and Y occurrences of character 'b'. Examples: Input: X = 2, Y = 3, K = 3Output: abbabExplanation: First lexicographical smallest string = "aabbb".Second lexicographical smallest string = "ababb".Third lex
20 min read
Find character at Kth index by appending S1 (M) times and S2 (M+1) times
Given two strings, S1 and S2 and an integer K.A string str can be made by performing the following operations: Take an Empty String InitiallyAppend S1 one timesAppend S2 two timesAppend S1 three timesAppend S2 four timesAppend S1 five timesAppend S2 six timesYou can keep building this string until it reaches K The task is to find the character at t
15 min read
Shortest String formed by concatenating string A x times and B y times such that n(A)*x = n(B)*y
Given two strings A and B, the task is to find the shortest string which is some multiple of both A and B. A string X is said to be a multiple of string Y if string X can be formed by the concatenation of multiple occurrences of string Y. Example: Input: A = "aaa", B= "aa"Output: aaaaaaExplanation: Multiplying A two times and B three times will res
7 min read
Count of Subarray with B times Sum equal to C times Length
Given, an array A[] of N integers, and also given two positive integers B and C, the task is to find the number of subarrays, such that B* Sum of elements of the subarray = C * Length of the subarray (here * describes multiplication). Examples: Input: N = 3, A[] = {3, -1, 1}, B = 1, C = 1Output: 3Explanation: The subarrays satisfying the conditions
7 min read
Article Tags :
Practice Tags :