Best way to deal with - hours returned from ctime

Hey guys. I'm making a world clock derived from local clock. The world clock class is inherited from the local clock. I'm looking for a better way to output the hours without using 10 different if/else statements. The time is displayed in military or standard depending on if the clock is military or not.

Here is my get hours function with the difference being the + or - from my local time.
1
2
3
4
5
6
7
8
9
  int Clock::get_hours() const               // return hours from ctime tm struct as an int
{
    time_t rawtime;
    struct tm *info;
    info = new tm;
    time( &rawtime );
    info = localtime( &rawtime );
    return info->tm_hour+difference;
}

My question is how would i account for negative time or time over 24, and accounting for standard time and the AM PM. Here was my code for the local time.
1
2
3
4
5
6
7
8
9
10
11
12
13
void Clock::displayClock() const           // Display the time if military use military if not use standard           
{
	int hours = get_hours();
	int minutes = get_minutes();
	if(military)
	{
		cout << get_location() << " time is " << hours << ":" << setfill('0') << setw(2) << minutes << endl;
	}
	else
	{
		cout << get_location() << " time is " << ((hours == 00 || hours == 12) ? 12 : hours % 12) << ":" << setfill('0') << setw(2) << minutes << (hours < 12 || hours > 24 ? " AM" : " PM") << endl; 
	}	
}

I tried ((hours > 24 || hours < 0) ? hours % 12 : hours) for military time it worked for hours over 24 but still returned - hours if under 0.
Last edited on
You should handle out of the normal range hours in get_hour() function and do not let such hours escape.
Look at the example here and apply something similar to your case: http://en.cppreference.com/w/cpp/chrono/c/mktime
Topic archived. No new replies allowed.