我想制作上个月的第一天和最后一天的数组。从我开始 \DateTime $date=2018-04-30。当我将开始更改\DateTime为2018-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"}}