简体   繁体   中英

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

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;
    }

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM