April 18th, 2009

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!

  • Share/Bookmark

2 Responses to ' Get the first & last day of the month with PHP '

Subscribe to comments with RSS or TrackBack to ' Get the first & last day of the month with PHP '.

  1. soho said,

    on May 14th, 2009 at 9:56 am

    return date("m/01/Y");

  2. 1mr3yn said,

    on September 29th, 2009 at 2:17 am

    Thanks for the nice post. That idea lead me to the algorithm that I need.

Leave a reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word