picture picture
November 23, 2009 PHP 0 Comments

Find start and end date of week in PHP

I need to check if the current day is a Monday and then figure out the dates of last week’s Monday and Sunday. Here is my solution which is simpler:

[code type=php]
if(date(‘N’) == 1) {
$prior_week = date(‘W’) – 1;
if($prior_week == 0) {
$prior_week = 52;
$year = date(‘Y’) – 1;
}else
$year = date(‘Y’);

echo date(“Y-m-d”, strtotime($year.’W’.$prior_week.’1′));
echo date(“Y-m-d”, strtotime($year.’W’.$prior_week.’7′));
}

?>
[/code]

So if we have a Monday which we have when date(‘N’) is 1, we get the current week number of the year with date(‘W’). Last week’s number should then be that number minus one. Note that we need to take extra precautions to to switch the year to the prior year if we have to.

Finally we use the old date and strtotime combo to get the dates in any format we want, in this case as YYYY-MM-DD. The format used in the strtotime call is an ISO8601 format that incorporates the day of week number and the week of year number. Without strtotime’s ability to understand this format the above solution would not work.