我想创建一个函数来从星期数和年份中获取天数列表作为参数。
我试图编写以下函数,该函数仅在我的周数大于10时有效。
public function getDaysofWeek(int $year, int $week){
// ...
$days = array();
for($d=1; $d<8; $d++) {
$days[] = date('d/m/Y', strtotime($year."W". $week .$d));
}
var_dump($days);
// ...
对于2019年的第37周(今天的一周),我得到了(实际上是正确的结果):
array(7) { [0]=> string(10) "09/09/2019"
[1]=> string(10) "10/09/2019"
[2]=> string(10) "11/09/2019"
[3]=> string(10) "12/09/2019"
[4]=> string(10) "13/09/2019"
[5]=> string(10) "14/09/2019"
[6]=> string(10) "15/09/2019" }
但是当我的星期数少于10时,我得到了(这里,2019年第05周):
array(7) { [0]=> string(10) "16/12/2019"
[1]=> string(10) "23/12/2019"
[2]=> string(10) "30/12/2019"
[3]=> string(10) "01/01/1970"
[4]=> string(10) "01/01/1970"
[5]=> string(10) "01/01/1970"
[6]=> string(10) "01/01/1970" }
我不明白为什么会发生此问题,有人 解释或解决方案?
答案 0 :(得分:3)
问题在于,当您在一周中使用整数时,将其构建为日期中的
$days[] = date('d/m/Y', strtotime($year."W". $week .$d));
由于日期格式不正确(2019W5
),您最终会遇到错误,您需要确保一周的数字为2位数。
这只是格式化一周,以确保其显示为2019W05
...
$days[] = date('d/m/Y', strtotime($year."W".
sprintf("%02d", $week) .$d));