Domanda

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.

È stato utile?

Soluzione

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top