简体   繁体   English

PHP-当星期在星期一以外的日子开始时,获取给定星期数的第一天

[英]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: 在我的PHP应用程序中,我具有三个变量:

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 在这种情况下,2014年的第一周(该周从星期六开始)为 December 28th. 12月28日。 2014-01-04. 2014年1月4日。

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: 使用DateTime::setISODate ,其中第三个参数是星期几:

$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 演示 演示#2


Your example isn't working, because you are using format yyyyWweek , which is by default Monday. 您的示例不起作用,因为您使用的格式为yyyyWweek ,默认情况下为星期一。 Read about ISO-8601 formats , and you will see that there is format yyyy-Wweek-day , which you can use like: 阅读有关ISO-8601格式的信息 ,您将看到有yyyy-Wweek-day格式,您可以像这样使用:

$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 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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