The best way to get the first and last day of last month?

Solution 1:

In PHP 5.3, you can use the DateTime class :

<?php

$month_ini = new DateTime("first day of last month");
$month_end = new DateTime("last day of last month");

echo $month_ini->format('Y-m-d'); // 2012-02-01
echo $month_end->format('Y-m-d'); // 2012-02-29

Solution 2:

Last day of the previous month:

date("Y-m-d", mktime(0, 0, 0, date("m"), 0));

First day of the previous month:

date("Y-m-d", mktime(0, 0, 0, date("m")-1, 1));

Solution 3:

I use these in MySQL and PHP scripts, short and simple:

echo date('Y-m-d', strtotime('first day of last month'));
echo date('Y-m-d', strtotime('last day of last month'));

MySQL use example:

$query = $db->query("SELECT * FROM mytable WHERE 1 AND mydate >= '".date('Y-m-d', strtotime('first day of last month'))."'");

Solution 4:

If you're doing this for the purpose of a MySQL query, have you considered using the MONTH function, e.g.

SELECT [whatever stats you're after] FROM table
WHERE MONTH(date_field) = 12 and YEAR(date_field) = 2011

This would get your stats for December. If you start to experience performance problems and the historical data doesn't change, you might want to denormalise the data into an aggregate table (rolled up by the smallest increment you need, e.g. daily/hourly/monthly etc).