I want to make array of previous month 1st and last day. From my starting \DateTime $date=2018-04-30
. When I change my starting \DateTime
to 2018-05-31
and my expected result is an array that contains:
[
['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],
]
I have currently done:
$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');
Result array:
$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],
];
My code generates:
{"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 "}
}
}
What is best option to solve my problem? I was planning to make strings and create new DateTime
for each array record, but want to be sure if there are no other way to do this.
Still wrong:
"yearAgo":{ "start":{"date":"2017-04-30"}}
"ago3month":{"end":{"date":"2017-12-31"}}
---edit---
I used Carbon library that solves my issue. Similar question here,