Getting start and end date of week in PHP

I just searched for ways of getting the start and end dates of a week. Sadly there is some less than simple solutions in the top results, this is a small effort at remedying that situation.

My problem is that given any day 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 than many others out there:

if(date('N') == 1){
    $prior_week = date('W') - 1;
    if($prior_week == 0){
		$prior_week = 52;
		$year = date('Y') - 1;
		$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'));

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.

Related Posts

Tags: ,