获得当前周/年的所有周

时间:2016-01-26 08:22:34

标签: php date

我有以下代码,这些代码在过去的一周内持续了52周。我想修改它以便它只包括当前年份。所以它应该只显示1月的前4周。

public static function weeks()
{
    $nextWeek = strtotime('+1 week');

    for($i=0;$i<52;$i++) 
    {
        $date   = date('Y-m-d', strtotime('-'.$i.' week'));
        $nbDay  = date('N', strtotime($date));
        $monday = new \DateTime($date);
        $sunday = new \DateTime($date);
        $monday->modify('-'.($nbDay-1).' days');
        $sunday->modify('+'.(7-$nbDay).' days');

        if($nextWeek > strtotime($sunday->format('Y-m-d'))) {
            $weeks[$monday->format('W')] = $monday->format('j M Y') . ' - ' . $sunday->format('j M Y');
        }
    }

    return $weeks;
}

如何修改代码?

1 个答案:

答案 0 :(得分:2)

你可以使用date()W一年中的一周作为循环的上限吗?

public static function weeks()
{
    $nextWeek = strtotime('+1 week');
    /* change the upper bound of the loop using `date('W')` */
    for( $i=0; $i < date('W'); $i++ ) 
    {
        $date   = date('Y-m-d', strtotime('-'.$i.' week'));
        $nbDay  = date('N', strtotime($date));

        $monday = new \DateTime($date);
        $sunday = new \DateTime($date);

        $monday->modify('-'.($nbDay-1).' days');
        $sunday->modify('+'.(7-$nbDay).' days');

        if($nextWeek > strtotime($sunday->format('Y-m-d'))) {
            $weeks[$monday->format('W')] = $monday->format('j M Y') . ' - ' . $sunday->format('j M Y');
        }
    }

    return $weeks;
}
相关问题