PHP: Getting dates from Monday to Friday of last week

These will get you the dates of the previous Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Saturday.

date("Y-m-d", strtotime("previous monday"));
date("Y-m-d", strtotime("previous tuesday"));
date("Y-m-d", strtotime("previous wednesday"));
date("Y-m-d", strtotime("previous thursday"));
date("Y-m-d", strtotime("previous friday"));
date("Y-m-d", strtotime("previous saturday"));
date("Y-m-d", strtotime("previous sunday"));

If the current day is tuesday, and you want to get the monday of last week, then the previous monday will not get the monday you want, it will get the date of the monday just the day before tuesday. To get the dates from Monday to Friday of the last week, we need to calculate the difference between the previous monday from the strtotime function and the current date, if the difference is less than 7 that means the monday is within the current week. If it is the monday of the current week, then we can apply the previous monday one more time to get the monday of last week. The function below returns an array of the dates from Monday to Sunday of the last week.

function getLastWeekDates()
{
	$lastWeek = array();

	$prevMon = abs(strtotime("previous monday"));
	$currentDate = abs(strtotime("today"));
	$seconds = 86400; //86400 seconds in a day

	$dayDiff = ceil( ($currentDate-$prevMon)/$seconds ); 

	if( $dayDiff < 7 )
	{
		$dayDiff += 1; //if it's monday the difference will be 0, thus add 1 to it
		$prevMon = strtotime( "previous monday", strtotime("-$dayDiff day") );
	}

	$prevMon = date("Y-m-d",$prevMon);

	// create the dates from Monday to Sunday
	for($i=0; $i<7; $i++)
	{
		$d = date("Y-m-d", strtotime( $prevMon." + $i day") );
		$lastWeek[]=$d;
	}

	return $lastWeek;
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search