-1

我想制作上个月的第一天和最后一天的数组。从我开始 \DateTime $date=2018-04-30。当我将开始更改\DateTime2018-05-31并且我的预期结果是一个包含以下内容的数组时:

[
  ['2018-03-01', 2018-03-31],
  ['2018-02-01', 2018-02-28],
  ['2018-01-01', 2018-01-31],
  ['2018-01-01', 2018-03-31],
  ['2017-03-01', 2018-03-31],
]

我目前已经完成:

$monthAgoStart = clone $date;
$monthAgoEnd = clone $date;
$month2agoStart = clone $date;
$month2agoEnd = clone $date;
$month3agoStart = clone $date;
$month3agoEnd = clone $date;
$currentYearStart = clone $date;
$yearAgo = clone $date;
$monthAgoStart->modify('first day of previous month');
$monthAgoEnd->modify('last day of previous month');
$month2agoStart->modify('first day of this month')->modify('-2 months');
$month2agoEnd = new \DateTime($month2agoEnd->modify('-1 months')->format('y-m-0'));
$month3agoStart= new \DateTime($month3agoStart->modify('-3 months')->format('y-m-1'));
$month3agoEnd = new \DateTime($month3agoEnd->modify('-3 months')->format('y-m-0'));
$currentYearStart->modify('first day of January');
$yearAgo->modify('-12 months');

结果数组:

$dates = [
  'ago1month' => ["start" => $monthAgoStart, "end" => $monthAgoEnd],
  'ago2month' => ["start" => $month2agoStart, "end" => $month2agoEnd],
  'ago3month' => ["start" => $month3agoStart, "end" => $month3agoEnd],
  'yearStart' => ["start" => $currentYearStart, "end" => $monthAgoEnd],
  'yearAgo' => ["start" => $yearAgo, "end" => $monthAgoEnd],
];

我的代码生成:

{"ago1month":{
         "start":{"date":"2018-03-01"},
         "end":{"date":"2018-03-31"}
    },
    "ago2month":{
         "start":{"date":"2018-02-01"},
         "end":{"date":"2018-02-28 "}
    },
    "ago3month":{
         "start":{"date":"2018-01-01 "},
         "end":{"date":"2017-12-31"}
    },
    "yearStart":{ 
        "start":{"date":"2018-01-01"},
        "end":{"date":"2018-03-31"}
    },
"yearAgo":{ 
        "start":{"date":"2017-04-30"},
        "end":{"date":"2018-03-31 "}
    }
}

解决我的问题的最佳选择是什么?我打算new DateTime为每个数组记录制作字符串并创建,但想确定是否没有其他方法可以做到这一点。还是错了: "yearAgo":{ "start":{"date":"2017-04-30"}} "ago3month":{"end":{"date":"2017-12-31"}}

4

1 回答 1

2

检索当月的最后一天时,您应该使用tfrom日期格式

您还可以通过在需要时克隆 $date 或使用 DateTimeImmutable 来简化代码并使其更易于阅读。

$month3agoEnd = (clone $date)->modify('-3 months')->format('Y-m-t');

事实证明这是2018-03-31预期的。使用您在新的 \DateTime 对象中处理的Y-m-0返回2018-03-0值,因此您的代码实际上写为:

 $month3agoEnd = new DateTime('2018-03-0');

这实际上返回了一个新的 DateTime 实例,2018-02-28因此我不确定您是如何获得2017-12-31.

于 2018-07-20T13:32:15.717 回答