0

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;
    }
smuhero
  • 19
  • 10

2 Answers2

2

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.

stefaanv
  • 14,072
  • 2
  • 31
  • 53
  • What did you mean by since midnight? – smuhero Aug 13 '14 at 12:11
  • 2:20:10 is at 7200+1200+10 seconds since midnight – stefaanv Aug 13 '14 at 12:51
  • I assume that it's home work so he is probably forbidden from using a "non self" written code like the `time.h` struct. Other that that you have my up vote. – Dima Maligin Aug 13 '14 at 13:03
  • @DimaMaligin: you're probably right, but that is why I gave advice and not the code. So with the answers combined, it should be obvious. – stefaanv Aug 13 '14 at 13:20
  • I spend hours last night at this. was only needed to add hours into the current hour1 - hour2 inside a conditional statement to create 24hr format. cheers. – smuhero Aug 13 '14 at 20:29
0

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;

Dima Maligin
  • 1,386
  • 2
  • 15
  • 30