Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Q&A: How do I figure out what the last day of the month is?

I was trying to write a roll-your-own timezone converter and I needed a way of determining what the last possible day of the month was. Upon some research, I discovered the formulas for finding a leap year.

It's a small contribution, but maybe I'll save someone else the 20 minutes it took me to figure out and apply it.

This code accepts a signed short month, indexed at 0 (0 is January) and an int year that is indexed as 0 as well (2012 is 2012).

It returns a 1 indexed day (the 27th is the 27th, but in SYSTEMTIME structures, etc., you usually need 0 indexed - just a head's up).

like image 275
Collin Biedenkapp Avatar asked Dec 31 '25 13:12

Collin Biedenkapp


1 Answers

short _get_max_day(short month, int year) {
    if(month == 0 || month == 2 || month == 4 || month == 6 || month == 7 || month == 9 || month == 11)
        return 31;
    else if(month == 3 || month == 5 || month == 8 || month == 10)
        return 30;
    else {
        if(year % 4 == 0) {
            if(year % 100 == 0) {
                if(year % 400 == 0)
                    return 29;
                return 28;
            }
            return 29;
        }
        return 28;
    }
}
like image 120
Collin Biedenkapp Avatar answered Jan 02 '26 03:01

Collin Biedenkapp