我的代码中有开始和结束日期选择器选项。任何用户都可以选择开始和结束周来获取每周数据。
我希望获得周数和年份但是如果我选择2017-01-01作为开始日期,并且将2017-02-25作为结束日期,它将显示从第一季度开始的第52周和第2017周。有没有办法获得正确的一周和一年?
$start = new DateTime($event->data['requestData']['input_from']); //it takes start date
$end = new DateTime($event->data['requestData']['input_to']); //it takes end date
$interval = new DateInterval('P1W');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
$newItems[$dt->format('Y.W')] = array('year' => $dt->format('Y'), 'week'=> $dt->format('W'));
}
输出:
Array
(
[2017.52] => Array
(
[year] => 2017
[week] => 52
)
[2017.01] => Array
(
[year] => 2017
[week] => 01
)
[2017.02] => Array
(
[year] => 2017
[week] => 02
)
[2017.03] => Array
(
[year] => 2017
[week] => 03
)
[2017.04] => Array
(
[year] => 2017
[week] => 04
)
[2017.05] => Array
(
[year] => 2017
[week] => 05
)
[2017.06] => Array
(
[year] => 2017
[week] => 06
)
[2017.07] => Array
(
[year] => 2017
[week] => 07
)
)
答案 0 :(得分:3)
您应该阅读Reference的定义。 1月1日不是第1周的定义。周编号从星期一开始,所以如果1月1日是星期日,就像2017年的情况一样,它在技术上是在上一年的第52周(即使它在它自己的一年。)
因此,您的代码在技术上会给您正确的结果:2017年1月1日是2017年,但也是在第52周(2016年)。
答案 1 :(得分:0)
我已经解决了这个问题。在格式中使用" o" 说明符来显示" ISO-8601年份编号" 而不是当前年份。将 $ dt->格式(' Y.W')更改为 $ dt->格式(' o.W')强>如下
foreach ($period as $dt) {
$newItems[$dt->format('o.W')] = array('year' => $dt->format('o'), 'week'=> $dt->format('W'));
}
输出:
Array
(
[2016.52] => Array
(
[year] => 2016
[week] => 52
)
[2017.01] => Array
(
[year] => 2017
[week] => 01
)
[2017.02] => Array
(
[year] => 2017
[week] => 02
)
[2017.03] => Array
(
[year] => 2017
[week] => 03
)
[2017.04] => Array
(
[year] => 2017
[week] => 04
)
[2017.05] => Array
(
[year] => 2017
[week] => 05
)
[2017.06] => Array
(
[year] => 2017
[week] => 06
)
[2017.07] => Array
(
[year] => 2017
[week] => 07
)
)