PHP DateTime : 获取与上一年相比的当前 week/month/year 间隔(开始-结束)

PHP DateTime : get current week/month/year interval (start-end) compared with the previous year

Today is 2015-05-22 (to understand the example)

我必须查看一些从数据库中获取值的统计数据。最初我不得不做这些比较

对于所有这些控件,我执行了计算所有不同日期间隔的函数。

function getIntervalDate(){

    $today = new DateTime();
    $appToday = new DateTime();

    $numDay = date("w");
    $numYear = (int)date("Y");

    switch($numDay){
        //monday
        case 1 : 
            $startWeek = $today->format('Y-m-d 00:00:00');
            $endWeek = $today->modify('next sunday')->format('Y-m-d 23:59:59');

            $startWeek2 = $today->modify('last monday -1 week')->format('Y-m-d 00:00:00');
            $endWeek2 = $today->modify('next sunday')->format('Y-m-d 00:00:00');

        break;
        default:
            $startWeek = $today->modify('last monday')->format('Y-m-d 00:00:00');
            $endWeek = $today->modify('next sunday')->format('Y-m-d 23:59:59');

            $startWeek2 = $today->modify('last monday -1 week')->format('Y-m-d 00:00:00');
            $endWeek2 = $today->modify('next sunday')->format('Y-m-d 00:00:00');

        break;
    }

    $startMonth = $today->modify('first day of this month')->format('Y-m-d H:i:s');
    $endMonth = $today->modify('last day of this month')->format('Y-m-d 23:59:59');

    $today1 = $appToday;

    $startMonth2 = $today1->modify('first day of previous month')->format('Y-m-d H:i:s');
    $endMonth2 = $today1->modify('last day of this month')->format('Y-m-d 23:59:59');

    $today2 = $appToday;

    $startYear = $today2->modify('first day of January '.$numYear)->format('Y-m-d 00:00:00');
    $endYear = $today2->modify('last day of December '.$numYear)->format('Y-m-d 23:59:59');

    $today3 = $appToday;

    $startYear2 = $today3->modify('first day of January '.($numYear-1))->format('Y-m-d 00:00:00');
    $endYear2 = $today3->modify('last day of December '.($numYear-1))->format('Y-m-d 23:59:59');

    return array(

        "startWeek" => $startWeek,
        "endWeek" => $endWeek,
        "startWeek2" => $startWeek2,
        "endWeek2" => $endWeek2,

        "startMonth" => $startMonth,
        "endMonth" => $endMonth,
        "startMonth2" => $startMonth2,
        "endMonth2" => $endMonth2,

        "startYear" => $startYear,
        "endYear" => $endYear,
        "startYear2" => $startYear2,
        "endYear2" => $endYear2

    );

}

一切正常。但是现在我必须改变各种比较。我必须始终比较当前的周/月/年间隔但与上一年的周/月/年(在年份没有问题的情况下,代码仍然存在相同)

我做了一些测试,但我失败了。我主要使用 ->modify('-1 year') 但结果并不完美。

根据您上面的讨论,这里是您问题的解决方案:

$startWeek->modify("-1 year")->modify('monday')->format('Y-m-d H:i:s');

这是测试。

$today = DateTime::createFromFormat('Y-m-d H:i:s', '2015-05-18 00:00:00');
$startWeekPrevYear=$today->modify('-1 year')->modify('monday');

echo $startWeekPrevYear->format('Y-m-d H:i:s');//outputs 2014-05-19 00:00:00