With PHP DateTime you can use methods such as ->modify()
->add()
and ->sub()
to manipulate the current DateTime object.
There are also ->setDate()
and ->setTime()
methods which allow updating of the year, month and day, or the hour, minute and second.
There doesn’t however appear to be any way to just set the year, month or day alone.
Am I right in thinking that the best method is to create a new DateTime object and use the previous object to populate the setDate()
method?
Something like this:
$DateTime2020 = new DateTime('2020-02-26'); $DateTime2019 = (new DateTime())->setDate('2019', $DateTime2020->format('m'), $DateTime2020->format('d'));
Advertisement
Answer
$DateTime2020 = new DateTime('2020-02-26'); $year = 2019; $DateTime2019 = date_create($DateTime2020->format($year."-m-d")); // 2019-02-26 00:00:00.000000