Elapsed time between two time in 24hr format hh:mm:ss

2k Views Asked by At

Hey thanks for dropping in. I just wan't to say i do apologize if anybody has came across this question before.

I have spend hours searching through the forums and google for a similar problems, but no luck so far.

My intention for this program is to print out the elapsed time between two time which are in 24hr format.

As of now i think i only got my head around to convert the elapse 1st and 2nd "hh" into correct 24 time, but having trouble understanding how to do minutes and seconds.

I really appreciate any guidance, it would be really helpful. cheers.

    int main()
    {
        char time1[ 48 ] = "14:48:34";
        char time2[ 48 ] = "02:18:19";

        int hour1;
        int min1;
        int sec1;

        int hour2;
        int min2;
        int sec2;

        int seconds;
        int temp;

        //time1
        hour1 = atoi( strtok( time1, ":" ) );
        min1 = atoi( strtok( NULL, ":" ) );
        sec1 = atoi( strtok( NULL, ":" ) );

        //time2
        hour2 = atoi( strtok( time2, ":" ) );
        min2 = atoi( strtok( NULL, ":" ) );
        sec2 = atoi( strtok( NULL, ":" ) );

        seconds = hour1 * 60 * 60; //convert hour to seconds
        ...

        system("PAUSE");
        return 0;
    }
3

There are 3 best solutions below

5
On BEST ANSWER

Don't take the difference between hours, minutes and seconds. Convert both times to seconds since midnight and take the difference between these. Then convert back to hh:mm:ss.

By the way: there are structs and functions in time.h that can help.

0
On
#include <stdio.h>

int main() {
    int h1, m1, s1, h2, m2, s2;
    
    // Input the first time
    scanf("%d:%d:%d", &h1, &m1, &s1);
    
    // Input the second time
    scanf("%d:%d:%d", &h2, &m2, &s2);
    
    // Calculate the total elapsed time in seconds
    int totalSeconds1 = h1 * 3600 + m1 * 60 + s1;
    int totalSeconds2 = h2 * 3600 + m2 * 60 + s2;
    
    int elapsedTime = totalSeconds2 - totalSeconds1;
    
    // Output the difference in seconds
    printf("%d\n", elapsedTime);

    return 0;
}
2
On

Assuming that the times are in the same day(same date) the best way to solve you problem is by converting the times to a seconds from midnight format like:

long seconds1 = (hours1 * 60 * 60) + (minutes1 * 60) + seconds1;

long seconds2 = (hours2 * 60 * 60) + (minutes2 * 60) + seconds2;

long deference = fabs(seconds1 - seconds2);

then convert the deference back to h:m:s format like;

int hours = deference / 60 / 60;

int minutes = (deference / 60) % 60;

int seconds = deference % 60;