如何正确地在两天之间获得日历周

时间:2015-01-07 08:44:45

标签: php arrays calendar

您好我需要一个代码来获取两个日期之间的周日历数字。我从这里稍微考虑了一些代码,但总是得到错误的日历编号。

第一个代码:

    $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周的日历不在?

1 个答案:

答案 0 :(得分:0)

你的第二个代码会像你期望的那样返回结果:

$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                                                              
)