简体   繁体   中英

PHP - get first day of a given week number when week starts on day other than Monday

In my PHP app I have three variables:

Code:

$year = 2014
$weeknumber = 1
$weekstarts = 6 //Week starts on Saturday. 1=Monday... 6=Saturday and 7=Sunday

With these three parameters I would like to figure out what is the first day of the week. In this case, the 1st week of 2014, when the week starts on Saturday, is December 28th. 2014-01-04.

For weeks that start on Monday I can easily figure this out with:

Code:

$first_day_of_week = strtotime( $year . "W" . "0".$weeknumber)

But it does not work for weeks starting in days other than Monday.

Use DateTime::setISODate , where 3rd parameter is day of the week:

$dt = new DateTime;
echo $dt->setISODate(2014, 1, 0)->format('Y-m-d'), "\n"; # 0 = Sunday
echo $dt->setISODate(2014, 1, 1)->format('Y-m-d'), "\n"; # 1 = Monday
echo $dt->setISODate(2014, 1, 6)->format('Y-m-d'), "\n"; # 6 = Saturday

demo demo #2


Your example isn't working, because you are using format yyyyWweek , which is by default Monday. Read about ISO-8601 formats , and you will see that there is format yyyy-Wweek-day , which you can use like:

$format = sprintf("%d-W%02d-%d", $year, $weeknumber, $weekstarts == 7 ? 0 : $weekstarts);
$first_day_of_week = strtotime($format);
echo "$format returned $first_day_of_week\n";

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM