Finding the last day of the month.

While installing a scheduler we came across the need to create a scheduler that would readily create the date for the last day of the month. We needed this so the scheduler could be passed a date range which would be the current date to the last day of the month. There are lots of ways of finding the last day of the month such as creating an array of the last days of the month and then addressing that array based on the current month. The only problem with this is the leap year adjustment which has a number of rules to follow such as a year that is a multiple of by 4 is a leap year, a Year that is a multiple of 100 is not a leap year, but a year that is a multiple of 400 is a leap year. Programming the logic would be fairly simple so we thought that would be the route we would take until we came across another approach, the suggestion was to find the first day of next month and subtract 1 day from it. So that is what we did and here is the code which we used.


int main(int argc, char** argv) {
struct tm conv,*curr; // date structure and pointer
time_t lastday,now; // long variables for seconds since epoch

// set the conversion structure to first day of month and 00:00:00
conv.tm_hour = 0;
conv.tm_min = 0;
conv.tm_sec = 0;
conv.tm_mday = 1;

now = time(NULL);
curr = gmtime(&now);
// if december increment the year and set to january
if(curr->tm_mon == 12) {
conv.tm_mon = 0;
conv.tm_year = curr->tm_year + 1;
else {
conv.tm_mon = curr->tm_mon + 1;
conv.tm_year = curr->tm_year;
//convert the date to seconds
lastday = mktime(&conv);
// Subtract 1 day
lastday -= 68400;
// Convert back to date and time
conv = *localtime(&lastday);

That was it, a very simple piece of code which allows us to determine the last day of the month.


Article Global Facebook Twitter Myspace Friendfeed Technorati Digg Google StumbleUpon Eli Pets

This entry was posted in C Programming System i5 by Chris Hird. Bookmark the permalink.

About Chris Hird

Chris Hird President and Owner Shield Advanced Solutions. Hird first worked with high availability at IBM Havant in the United Kingdom in 1989, and he was responsible for the technical interface with the developers of HA products and setting up a support structure in the UK to support the IBM customers. He left IBM to set up Shield Software Services in 1993, which was an IBM business partner and a MiMiX reseller, and in 1997 he moved to Canada and launched Shield Advanced Solutions, which provides tools and utilities aimed mainly at supporting HA Environments. Programs in C and PHP on the i5.

Leave a Reply