Get the first & last day of the month with PHP
This is a couple of rather simple functions that will return the first and last day of the current month. Of course, you could rig them up to return the first and last of any month, but that's up to you once you've got my code
.
These two little functions are greating in a situation where you need to create a date range of the entire current month.
Currently they return the date in the format of 04/01/2009 and 04/30/2009, but you could rig them up however you'd like by changing the date() format parameter.
Here's the PHP code for the functions:
function firstOfMonth() {
return date("m/d/Y", strtotime(date('m').'/01/'.date('Y').' 00:00:00'));
}
function lastOfMonth() {
return date("m/d/Y", strtotime('-1 second',strtotime('+1 month',strtotime(date('m').'/01/'.date('Y').' 00:00:00'))));
}
And here's how to use them:
$date_start = firstOfMonth();
$date_end = lastOfMonth();
Of course, firstOfMonth() is very simple. It just takes the current month, day 1, current year, and 12am as the time.
However, last of month isn't so simple, because you can't just plug in a default end day as you know the months vary in length. And you can't just make a simple array of 12 end dates, because that doesn't account for leap years. So, what this function does is takes the first day of next month, and subtracts a day! Ahh, there's beauty in the simplicity of it!


on May 14th, 2009 at 9:56 am
return date("m/01/Y");
on September 29th, 2009 at 2:17 am
Thanks for the nice post. That idea lead me to the algorithm that I need.