// File: whattime.cxx // Michael Main - Jan 28, 2003 // This program prints the time in the current time // zone. The constant ZONE_ADJUST should be set to // the number of seconds that the current time zone // differs from GMT. The constant ZONE_NAME should // be set to the current time zone name. There are // other ways to write this program that will work // correctly in any time zone, but we haven't yet // learned about those techniques. // // Note: The time(0) function used in this program // returns the number of seconds that have passed // since the start of 1970, using GMT. But this time // function will fail to work sometime in 2038 because // the long data type is not big enough to hold the // accumulated number of seconds. The exact time of // doom is Jan 19, 2038 at 3:14:08am GMT. There are // other time systems that count from 1900 with a data // type that will overflow at 6:28:17am on Feb 7, 2035. #include // Provides the time function #include // Provides cout #include // Provides the string class using namespace std; const long SECONDS_PER_MINUTE = 60; const long SECONDS_PER_HOUR = 60 * SECONDS_PER_MINUTE; const long SECONDS_PER_DAY = 24 * SECONDS_PER_HOUR; const long ZONE_ADJUST = -7 * SECONDS_PER_HOUR; const string ZONE_NAME = "Mountain Time"; void get_time (int& hour, int& minute, int& second, char& a_or_p); // This function sets the three reference parameters // (hour, minute and second) to the time in the // current time zone using a usual 12-hour clock. // The reference parameter a_or_p is set to 'a' if the // time is before noon and to 'p' on or after noon. int main( ) { int hour, minute, second; char a_or_p; get_time(hour, minute, second, a_or_p); cout << hour; cout << ":"; if (minute < 10) cout << "0"; cout << minute; cout << ":"; if (second < 10) cout << "0"; cout << second; cout << a_or_p << "m " << ZONE_NAME << endl; return 0; } void get_time (int& hour, int& minute, int& second, char& a_or_p) { long many_seconds; many_seconds = (time(0) + ZONE_ADJUST) % SECONDS_PER_DAY; hour = int(many_seconds / SECONDS_PER_HOUR); if (hour >= 12) { a_or_p = 'p'; if (hour > 12) { // Change 13 to 1pm, 14 to 2pm... hour = hour - 12; } } else { a_or_p = 'a'; if (hour == 0) { // Change the first hour of the day to 12am hour = 12; } } many_seconds = many_seconds % SECONDS_PER_HOUR; minute = int(many_seconds / SECONDS_PER_MINUTE); second = int(many_seconds % SECONDS_PER_MINUTE); }