### The Problem

Given a year and a month, I want to determine the last day of that month. For example, if the year is 2004 and the month is 2, then the last day is 29th because of leap year.

### The Solution

Calculating the last day of a month is not hard, but complicated by the leap year. If the year is a leap year, then February’s last day will be 29th instead of the usual 28th. My algorithm to find the last day of the month is simpler than that: take the first day of the next month and count backward by one day. Here is the code.

#!/usr/bin/env python import datetime def get_last_day_of_the_month(y, m): ''' Returns an integer representing the last day of the month, given a year and a month. ''' # Algorithm: Take the first day of the next month, then count back # ward one day, that will be the last day of a given month. The # advantage of this algorithm is we don't have to determine the # leap year. m += 1 if m == 13: m = 1 y += 1 first_of_next_month = datetime.date(y, m, 1) last_of_this_month = first_of_next_month + datetime.timedelta(-1) return last_of_this_month.day

### Discussion

The code above is easy enough to understand. The datetime.timedelta(-1) on line 22 basically says, “subtract one day.”

Advertisements

Donald Organwow in PHP you can just do:

date(‘t’, strtotime( ‘2011-04-01’ ) );HaiPost authorDonald: Excellent. I am not familiar with Python, thus the run-around algorithm. In fact Python has something similar to that: calendar.monthrange(2004, 2)[1]

pbC#:

return new DateTime(y, m, 01)

.AddMonths(1)

.AddDays(-1)

;

David WorkmanRuby on Rails (so with ActiveSupport’s datetime extensions):

DateTime.parse(“#{y}/#{m}/1”).end_of_month.day

HaiPost authorCool. Keep them coming. I love your solutions.

Rod.ne3I do not know if this is relevant. But in bash. Using date (GNU coreutils) 6.10

date –date=”1 day ago” “+%Y-%m-%d”