/* Defective Solution in C */ // converts the time represented by the tm structure pointed to by tmP into a calendar time (the number of seconds since 00:00:00 UTC, January 1, 1970) See: http://www.cplusplus.com/reference/ctime/tm/ static time_t tm_to_time( struct tm* tmP ) { time_t result; // monthtab[i] is the number of days in the months prior to i static int monthtab[12] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; result = ( tmP->tm_year - 70 ) * 365; result += ( tmP->tm_year - 69 ) / 4; result += monthtab[tmP->tm_mon]; result += tmP->tm_mday - 1; // 1-based field result = result * 24 + tmP->tm_hour; result = result * 60 + tmP->tm_min; result = result * 60 + tmP->tm_sec; return result; } /* Defective Solution in pseudocode */ // converts the time represented by the tm structure pointed to by tmP into a calendar time (the number of seconds since 00:00:00 UTC, January 1, 1970) static time_t tm_to_time( struct tm* tmP ) { time_t result; // monthtab[i] is the number of days in the months prior to i static int monthtab[12] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; // CONVERT the number of years since the start of the epoch into days. // ADD the number of leap days that have occurred in previous years. // ADD the number of days in the months before this one // ADD the number of days since the beginning of this month. // CONVERT days to hours and add the current hours // CONVERT the hours to minutes and add the current minutes // CONVERT the minutes to seconds and add the current seconds // Return the result } /* Correct solution */ // converts the time represented by the tm structure pointed to by tmP into a calendar time (the number of seconds since 00:00:00 UTC, January 1, 1970) static time_t tm_to_time( struct tm* tmP ) { time_t result; // monthtab[i] is the number of days in the months prior to i static int monthtab[12] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; // CONVERT the number of years since the start of the epoch into days. result = ( tmP->tm_year - 70 ) * 365; // ADD the number of leap days that have occurred in previous years. result += ( tmP->tm_year - 69 ) / 4; // ADD the number of days in the months before this one result += monthtab[tmP->tm_mon]; // IF we are past February and this year is a leap year THEN if ( tmP->tm_mon >= 2 && is_leap( tmP->tm_year + 1900 ) ) { // ADD one ++result; } // END IF // ADD the number of days since the beginning of this month. result += tmP->tm_mday - 1; // 1-based field // CONVERT days to hours and add the current hours result = result * 24 + tmP->tm_hour; // CONVERT the hours to minutes and add the current minutes result = result * 60 + tmP->tm_min; // CONVERT the minutes to seconds and add the current seconds result = result * 60 + tmP->tm_sec; // Return the result return result; }