PHP Get First and Last Day of Week by Week Number

I’m adding a simple post here with a PHP method that has helped me. This method calculates the beginning and ending of a week given the year and week number. The problem I’ve run into is that “first day of the week” is subjective. Some people believe the first day of the week is “Monday” while others believe the first day of the week is “Sunday”. ISO-8601 specifies the first day of the week as “Monday”. Whereas, most western calendars display Sunday as the first day of the week and Saturday as the last day of the week.

To add to the confusion, PHP’s methods themselves seem confused about what the first and last day of the week are.

For example:

$new_date = new DateTime;
// returns Monday, Jan 29 2018
$new_date->setISODate(2018, 5);

// returns Sunday, Feb 4 2018
$new_date->modify('sunday this week');

// returns Sunday, Jan 28 2018
$new_date->setISODate(2018, 5 ,0);

You’ll notice that the string “sunday this week” actually returns Sunday, Feb 4 whereas setting the date to the 0 day of the same week returns Sunday, Jan 28. I’m not saying that Sunday doesn’t happen twice a week… but Sunday doesn’t happen twice a week.

All this to say, the method below is the one I’ve found returns the most helpful results:

function get_first_and_last_day_of_week( $year_number, $week_number ) {
	// we need to specify 'today' otherwise datetime constructor uses 'now' which includes current time
	$today = new DateTime( 'today' );

	return (object) [
		'first_day' => clone $today->setISODate( $year_number, $week_number, 0 ),
		'last_day'  => clone $today->setISODate( $year_number, $week_number, 6 )
	];
}