Solution for Exercise 21-9

ex2109

#include <stdio.h>
#include <time.h>

int main()
{
    time_t tictoc;
    struct tm *today;
    int hour;
    char *am = "a.m.";
    char *pm = "p.m.";
    char *m;

    time(&tictoc);
    today = localtime(&tictoc);
    hour=today->tm_hour;
    if(hour==12)
    {
        m=pm;
    }
    else if(hour>12)
    {
        hour-=12;
        m=pm;
    }
    else
    {
        m=am;
    }
    printf("The time is %d:%02d:%02d %s\n",
        hour,
        today->tm_min,
        today->tm_sec,
        m);
    return(0);
}

Notes

* Several methods exist to properly solve this Exercise, so what you see above is only one variation.

* First, look at my solution at Line 29 for padding the output of the minutes and seconds. The %02d conversion character outputs an integer value two-digits wide and pads a 0 to keep that width if necessary. This was a fix I suggested for the solution to Exercise 21-8.

* Second, I chose to use preset strings to represent AM and PM, as defined at Lines 9 and 10. The char pointer m is set equal the proper string later in the code.

* To get the AM or PM string, you have to determine whether the hour is greater than 11; in the 24-hour time format, hours 00 through 11 are AM. But there's a problem with displaying the results in a 12-hour format: 12:00 noon is both PM and a value equal to 12. To fix this issue, an if/if-else/else type of decision structure is needed.

* The if statement at Line 16 weeds out the noon condition.

* The else-if statement at Line 20 takes care of the other afternoon hours. If the hour value is greater than 12, then it's PM, otherwise it's AM.

* The else statement at Line 25 deals with everything else, which should be only AM hours at that point.

* I could have used the today->tm_hour variable directly in the decision structure, but I need to modify that value later in the code, so I created and used the hour variable instead.

* If you want to tackle one more problem: Fix the output so that the midnight hour is shown as 12:00:00 and not 00:00:00. Have fun!