如何只使用DateTime列出一个月的第一天和最后一天



我想让上个月的第一天和最后一天的数组。从我开始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"}}

---编辑---

我使用了Carbon库来解决我的问题。类似的问题,

检索月份的最后一天时,应使用日期格式中的t

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

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

结果如预期的那样,这是2018-03-31。使用Y-m-0返回在一个新的\DateTime对象中处理过的2018-03-0,因此您的代码实际上写为:

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

这实际上返回了一个设置为2018-02-28的新DateTime实例,所以我不确定您是如何获得2017-12-31的。

最新更新