计算接下来X周的周开始/结束日期


Calculating week start/end dates for the next X weeks

我正在尝试用PHP构建一个函数,根据日期的不同,它会给我

本周(周日)20/8/12至26/8/12

接下来的一周+1(星期一至星期日)2012年8月27日至2012年9月2日

接下来的第+2周(星期一至星期日)2012年9月3日至12年9月9日

接下来的一周+3(周一至周日)

接下来的一周+4(周一至周日)

接下来的一周+5(周一至周日)

我试过用下面的,但有更干净的吗??

$week0_mon = date("Y-m-d", strtotime(date("Y").'W'.date('W')."1"));
$week0_sun = date("Y-m-d", strtotime(date("Y").'W'.date('W')."7"));
$week1_mon = date("Y-m-d", strtotime(date("Y-m-d", strtotime($week0_mon)) . " +1 week"));
$week1_sun = date("Y-m-d", strtotime(date("Y-m-d", strtotime($week0_sun)) . " +1 week"));
echo $week0_mon.' to '.$week0_sun.'<br />';
echo $week1_mon.' to '.$week1_sun.'<br />';

也许这将解决您的问题,它计算上一个星期一,并从这里开始一次添加一周。只需编辑for

$dOffsets = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
$prevMonday = mktime(0,0,0, date("m"), date("d")-array_search(date("l"),$dOffsets), date("Y"));
$oneWeek = 3600*24*7;$toSunday = 3600*24*6;
for ($i=0;$i<= 5;$i++)
{
    echo "Week +",$i," (mon-sun) ",
            date("d/m/Y",$prevMonday + $oneWeek*$i)," to ",
            date("d/m/Y",$prevMonday + $oneWeek*$i + $toSunday),"<br>";
}

这给了我

Week +0 (mon-sun) 20/08/2012 to 26/08/2012
Week +1 (mon-sun) 27/08/2012 to 02/09/2012
Week +2 (mon-sun) 03/09/2012 to 09/09/2012
Week +3 (mon-sun) 10/09/2012 to 16/09/2012
Week +4 (mon-sun) 17/09/2012 to 23/09/2012
Week +5 (mon-sun) 24/09/2012 to 30/09/2012

我已经调整@Wr1t3r的答案,以给出正确的日期范围,如下所示:

function plus_week($addWeek=0){
    $last_monday_timestamp=strtotime('-'.(date('N')-1).' days');
    if($addWeek!=0){
        if($addWeek>0) $addWeek='+'.$addWeek;
        $last_monday_timestamp=strtotime($addWeek.' week', $last_monday_timestamp);
    }
    $end_week_timestamp = strtotime ('+6 days', $last_monday_timestamp);
    return date('d/m/y', $last_monday_timestamp).' to '.date('d/m/y', $end_week_timestamp);
}

date('N')将给出周日的数字mon sun(1-7),所以如果我们从中减去1,我们就知道上周一还有多少天。或者我们可以使用strtotime("上周一")。但是,如果我们现在在周一,这种方式可以确保我们不会回到上周一。

星期一=1所以(1-1=0)-0天=今天
星期五=5所以(5-1=4)-4天=星期一
星期日=7(如果我们使用'w',则不是0),所以(7-1=6)-6天=星期一(不是明天)

我也调整了这一点,使周数为负数。

我是这样做的。我不确定这是否正是你想要的。

function plus_week($addWeek){
    $date = date("d.m.Y",time());
    $newdate = strtotime ( '+'.$addWeek.' week' , strtotime ( $date ) ) ;
    $newdate = date ( 'd/m/y' , $newdate );
    return $newdate;
}
for($i = 1; $i < 7; $i++){
    echo "Following week+".$i." ".plus_week($i)." to ".plus_week($i+1)."<br/>";
}

从这里你会得到这样的答案:

接下来的一周+1 2012年8月29日至2012年9月5日

接下来的一周+2 05/09/12至12/09/12

接下来的一周+3 12/09/12至19/09/12

接下来的一周+4 19/09/12至26/09/12

接下来的一周+5 2012年9月26日至2012年10月3日

接下来的一周+6 03/10/12至10/10/12