1

我正在尝试在 PHP 中构建一个函数,这取决于日期会给我

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

下周+1(周一至周日)27/8/12 至 02/9/12

下周+2(周一至周日)03/9/12 至 09/9/12

下周+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 />';
4

3 回答 3

1

也许这会回答你的问题,它计算上一个星期一并从这里开始一次添加一个星期。只需编辑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
于 2012-08-22T08:20:38.970 回答
0

I've adjusted @Wr1t3r answer to give correct date ranges as follows:

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') will give weekday number mon-sun (1-7) so if we subtract 1 from this we know how many days to go back to last monday. OR we could have used strtotime('last monday'). BUT this way ensures we dont go back to last monday if we are currently on monday.

Monday=1 so (1-1=0) -0 days = today
Friday=5 so (5-1=4) -4 days = monday
SUNDAY=7 (not 0 if we used 'w') so (7-1=6) -6 days = monday (not tomorrow)

I've also adjusted this to do negative week numbers too.

于 2012-08-22T08:24:32.730 回答
-1

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

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 29/08/12 至 05/09/12

下周+2 05/09/12 至 12/09/12

下周+3 12/09/12 至 19/09/12

下周+4 19/09/12 至 26/09/12

下周+5 26/09/12 至 03/10/12

下周+6 03/10/12 至 10/10/12

于 2012-08-22T08:02:51.993 回答