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 )
];
}
Cross Posting from https://jeremysawesome.com/2019/08/12/php-get-first-and-last-day-of-week-by-week-number/
Top comments (1)
this is nice