Calculating Months

I recently updated my Wambooli website’s front page to show only recent blog posts. I don’t regularly maintain the Wamblog any longer, so it was disappointing for me to see “recent posts” from ages ago. Therefore, I did a little coding to ensure that only recent posts appear or nothing.

What I wanted was to show only blog posts made within the past two months. The problem is to determine which posts are recent based on today’s date. While I wrote the code in PHP, it translates well into C: The core of the code is to get the sequential number for the current month.

For example, this month (November) is the 24,251st month since year zero:

2020 * 12 + 11

I’m not considering any oddball years when months were skipped or added. This detail isn’t necessary for my calculation.

After determining the current month number, I was able to use the same function on a blog post’s timestamp. Subtract one from the other, and if the difference is less than two months, it’s a “recent” blog post.

Your challenge for this month’s Exercise is to reproduce my monthcount() function. Given the current date or any date stored in a time_t variable, return an integer representing the current month count. Here is a programming skeleton to get you started:

2020_11_01-Lesson.c

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

int monthcount(time_t date)
{
}

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);
}

In my sample code, I obtain the count for the current month, though you can supply any time_t value as the function’s argument. The integer value returned is the month count. The solution involves manipulating the time_t value to extract years and months, doing a little math, then sending back the result.

Please try this Exercise on your own before you check out my solution.

Leave a Reply