//------------------------------------------------------------------- // secs2day.cpp // // This program implements an algorithm for displaying the date // in San Francisco after the prescribed number of seconds have // elapsed since the epoch-date occurred in Greenwich, England. // (The number of seconds is entered as a command-line argument // in order to facilitate automated testing of this algorithm.) // The standard UTC Epoch began at midnight on January 1, 1970, // and San Francisco is 8 hours behind Greenwich Mean Time. // // compile-and-link using: $ g++ secs2day.cpp -o secs2day // // programmer: ALLAN CRUSE // written on: 23 FEB 2007 //------------------------------------------------------------------- #include // for atoi() #include // for strncpy() #include // for printf() #define HOURS_PER_DAY 24 #define MINUTES_PER_HOUR 60 #define SECONDS_PER_MINUTE 60 #define MONTHS_PER_YEAR 12 #define DAYS_IN_USUAL_YEAR 365 #define DAYS_IN_LEAP_YEAR 366 #define UTC_EPOCH_YEAR 1970 #define SECONDS_PER_HOUR (SECONDS_PER_MINUTE * MINUTES_PER_HOUR) #define SECONDS_PER_DAY (SECONDS_PER_HOUR * HOURS_PER_DAY) #define DAYS_IN_4YR_CYCLE (DAYS_IN_USUAL_YEAR * 3 + DAYS_IN_LEAP_YEAR) #define MONTHS_IN_CYCLE (MONTHS_PER_YEAR * 4) char monthlist[ ] = "JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC "\ "JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC "\ "JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC "\ "JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC "; int monthdays[ ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int main( int argc, char **argv ) { if ( argc == 1 ) { printf( "argument is missing\n" ); return 1; } int seconds = atoi( argv[1] ); // adjust hours for timezone-delay, then calculate elapsed days int hours_since_epoch_GMT = seconds / SECONDS_PER_HOUR; int hours_since_epoch_PST = hours_since_epoch_GMT - 8; int days_since_epoch = hours_since_epoch_PST / HOURS_PER_DAY; // analyze the elapsed days in terms of repetitive 4-year cycles int cycles_since_epoch = days_since_epoch / DAYS_IN_4YR_CYCLE; int days_into_cycle = days_since_epoch % DAYS_IN_4YR_CYCLE; // now this loop will determine the day, month, and year int year = UTC_EPOCH_YEAR + (cycles_since_epoch * 4); int day = days_into_cycle; int month = 0; while ( month < MONTHS_IN_CYCLE ) { if ( day < monthdays[ month ] ) break; day -= monthdays[ month ]; ++month; } year += month / MONTHS_PER_YEAR; // extract the month's name from the monthlist char monthname[ 4 ] = {0}; strncpy( monthname, &monthlist[ month*4 ], 3 ); // adjust the day-number for "off-by-one" counting printf( " %02d %3s %4d \n", day+1, monthname, year ); }