Calculating Months – Solution

The task for this month’s Exercise is to return the month number for a time_t value. Effectively you extract the year and month, do some math, presto. Could it be this easy?

The key is to extract the month and year values from a time_t variable passed to the monthcount() function, as presented in the original post. And — this part is important — converting these values into their accurate representations.

Remember, a time_t variable stores years starting at 1901 and months starting with 0 for January. Here is my solution:

2020_11-Exercise.c

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

int monthcount(time_t date)
{
    struct tm *dstruct;
    int months;

    dstruct = localtime(&date);
    /* year is dstruct->tm_year + 1900 */
    /* month is dstruct->tm_mon + 1 */
    months = (dstruct->tm_year+1900) * 12;
    months += dstruct->tm_mon+1;

    return(months);
}

int main()
{
    int month;
    time_t now;

    time(&now);                    /* get the current date/time */
    month = monthcount(now);    /* calculate total number of months */
    printf("This month is number %d\n",month);

    return(0);
}

At Line 9, I use the localtime() function to fill a tm structure, dstruct, with details from the time_t value, date.

At Line 12, variable months is calculated as the current year multiplied by 12: months = (dstruct->tm_year+1900) * 12;. This value is increased by the current month value, plus one, to obtain the month count at Line 13. The result is returned at Line 15.

Here is a sample run (for today, 8 November 2020):

This month is number 24251

In my PHP code, I used this value to compare with the timestamp on a post. If the timestamp’s monthcount() return value was 2 less, the post isn’t listed. This technique is how I’m able to display only current posts. It’s a specific solution, but one that provided an interesting programming challenge.

I hope your solution meets with a good result. It’s possible to extract such information directly from a time_t value, though remember time_t is a cumulative total of seconds and not a bit field.

Leave a Reply