我想排列上个月的第一天和最后一天。从我的 <%= f.file_field :image_file, class: 'form-control' %>
开始。当我将起始 <%= image_tag "#{@user.image_file}" %>
更改为\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
答案 0 :(得分:2)
检索月份的最后一天时,应使用date format中的t
。
您还可以简化代码,并在需要时克隆$ date或使用DateTimeImmutable使其更易于阅读。
$month3agoEnd = (clone $date)->modify('-3 months')->format('Y-m-t');
原来是2018-03-31
。使用Y-m-0
返回2018-03-0
,您已经在新的\ DateTime对象中对其进行了处理,因此您的代码实际上写为:
$month3agoEnd = new DateTime('2018-03-0');
这实际上返回一个设置为2018-02-28
的新DateTime实例,所以我不确定您如何设法获得2017-12-31
。