PHP - 日期函数可以逐周返回一年中的时间

PHP - date function to go back in time week by week for a year

我有以下代码:

$last_week_start = date("Y-m-d",strtotime("monday last week"));
$last_week_end = date("Y-m-d",strtotime("sunday last week"));

for($i=52;$i>0;$i--){
    //do stuff with the dates for this week

    $last_week_start = date("Y-m-d",strtotime($last_week_start,"-7 days"));
    $last_week_end = date("Y-m-d",strtotime($last_week_end,"-7 days"));
}

它给我的最初两个日期是正确的,但是当我尝试跳回一周时,我收到一条错误消息 A non well formed numeric value encountered

我不确定为什么会这样或者我应该如何解决这个问题,任何建议都很好。

函数 strotime 在第一个参数中需要一个日期字符串,在第二个参数中需要一个时间戳作为基准时间。

您可以更改代码以使用 DateTime 对象并在此对象上操作日期。

<?php
$last_week_start = new \DateTime("monday last week");
$last_week_end = new \DateTime("sunday last week");

for($i=52;$i>0;$i--){
    //do stuff with the dates for this week

    $last_week_start->modify("-7 days");
    $last_week_end->modify("-7 days");
    $last_week_start_formatted = $last_week_start->format("Y-m-d");
    $last_week_end_formatted = $last_week_end->format("Y-m-d");
}

strtotime(time, now); Required. Specifies a date/time string

使用这种方式获取当前输出

date("Y-m-d",strtotime("-7 days",strtotime($last_week_start)))

<?PHP
    $last_week_start = date("Y-m-d",strtotime("monday last week"));
    $last_week_end = date("Y-m-d",strtotime("sunday last week"));
    echo $last_week_start." ".$last_week_end;
    for($i=52;$i>0;$i--){
        //do stuff with the dates for this week
    
        $last_week_start = date("Y-m-d",strtotime("-7 days",strtotime($last_week_start)));
        $last_week_end = date("Y-m-d",strtotime("-7 days", strtotime($last_week_end)));
    }
?>