1
votes

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.

1
It's really hard to tell what you're asking. Are you trying to find out what the previous Saturday for a given date is?davethegr8
Are we talking actual week numbers, or just 'whatever the first week was with a date in this year counting from my startday will be week 1'?Wrikken
@davethegr8 can you provide an implementation of your idea?oabarca
@Wrikken actual week numbersoabarca
So, the saturday of week 1 is 2014-01-04.. Which takes us to the question: if we change the day on which it starts: should we go forward , backward, or some custom rule?Wrikken

1 Answers

2
votes

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