[adrotate group=”3,7,8,9″]
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.
#include
#include
#include
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);
printf("%.4d%.2d%.2d",conv.tm_year+1900,conv.tm_mon+1,conv.tm_mday);
exit(0);
}
That was it, a very simple piece of code which allows us to determine the last day of the month.
Chris…