如何正确获取两天之间的日历周

How to get calendar weeks between two days correctly

您好,我需要一个代码来获取两个日期之间的周历数字。我使用此处的一些代码进行了一些测试,但总是得到错误的日历数字。

第一个代码:

    $startDateUnix = strtotime('2014-09-21');
$endDateUnix = strtotime('2014-10-06');

$currentDateUnix = $startDateUnix;

$weekNumbers = array();
while ($currentDateUnix < $endDateUnix) {
    $weekNumbers[] = date('W', $currentDateUnix);
    $currentDateUnix = strtotime('+1 week', $currentDateUnix);
}

print_r($weekNumbers);

第二个代码:

$start = '2014-09-22';
$end = '2014-10-06';
$dates = range(strtotime($start), strtotime($end),604800);
$weeks = array_map(function($v){return date('W', $v);}, $dates); // Requires PHP 5.3+
print_r($weeks);

我从两个代码中得到了这个:

Array ( [0] => 38 [1] => 39 [2] => 40 )

但为什么日历周 41 不在?

你的第二个代码 returns 结果如你所料:

$start = '2014-09-22';
$end = '2014-10-06';
$dates = range(strtotime($start), strtotime($end),604800);
$weeks = array_map(function($v){return date('W', $v);}, $dates); // Requires PHP 5.3+
print_r($weeks);

输出:

Array                                                                      
(                                                                          
    [0] => 39                                                              
    [1] => 40                                                              
    [2] => 41                                                              
)


您的第一个代码的问题是您从 2014-09-21 (KW 38) 开始并为每个循环添加一周。因此循环在结束日期之前结束。

您可以使用这样的第一个代码来解决此问题:

$startDateUnix = strtotime('2014-09-21');
$endDateUnix = strtotime('2014-10-06');

$currentDateUnix = $startDateUnix;

$weekNumbers = array();
while ($currentDateUnix <= $endDateUnix) {
    $weekNumbers[] = date('W', $currentDateUnix);
    $currentDateUnix = strtotime('+1 day', $currentDateUnix);
}
$weekNumbers = array_merge(array_unique($weekNumbers)); // array_merge to "reset" the keys
print_r($weekNumbers);

输出:

Array                                                                      
(                                                                          
    [0] => 38                                                              
    [1] => 39                                                              
    [2] => 40                                                              
    [3] => 41                                                              
)