Yesterday – Solution

The challenge for this month’s Exercise is to output yesterday’s date: the day of the week, day of the month, month, and year. It’s not as complex as it could be, though keep in mind that any code that outputs the proper result is valid.

My initial approach to solving this challenge was to use the localtime() function to obtain today’s data, then work backwards to retrieve yesterday’s data. You know: Subtract one from the day of the month, but then test to see if the result is zero and then adjust the other values accordingly. Such a solution is valid, but it’s a lot of work.

Instead, I considered the sole argument to the localtime() function: a time_t value. This value represents the number of seconds elapsed since the Unix Epoch of January 1, 1970. After obtaining today’s time_t value in the code, the sneaky way to obtain yesterday’s data is to subtract one day’s worth of seconds from the result, then call the localtime() function again with the updated time_t value.

One day’s worth of seconds is 60 * 60 * 24, or seconds_in_a_minute × minutes_in_an_hour × hours_in_a_day.

Here is my solution:

2023_05-Exercise.c

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

int main()
{
    time_t now;
    struct tm *today,*yesterday;
    const char *day[] = { "Sunday", "Monday",
        "Tuesday", "Wednesday", "Thursday",
        "Friday", "Saturday" };
    const char *month[] = { "January", "February",
        "March", "April", "May", "June", "July",
        "August", "September", "October",
        "November", "December" };

    /* get today's date */
    time(&now);
    today = localtime(&now);
    printf("Today is %s, %d %s %d\n",
            day[today->tm_wday],
            today->tm_mday,
            month[today->tm_mon],
            today->tm_year+1900
          );

    /* output yesterday's date */
    now -= 60*60*24;
    yesterday = localtime(&now);
    printf("Yesterday was %s, %d %s %d\n",
            day[yesterday->tm_wday],
            yesterday->tm_mday,
            month[yesterday->tm_mon],
            yesterday->tm_year+1900
          );

    return(0);
}

After today’s information is obtained, I subtract one day’s worth of seconds from variable now (today’s date and time). The localtime() function is called again with this updated time_t value. The results are saved in the new tm structure yesterday. The structure’s data is then output:

Today is Monday, 8 May 2023
Yesterday was Sunday, 7 May 2023

The more complex approach of manipulating various tm structure members is also valid, though not as brief as the solution above. As long as the output is accurate, consider that you passed the challenge.

Leave a Reply