如何将日期解析为上个月的同一天?

Raf*_*med 1 php datetime date-math

如何在 PHP 中解析日期到上个月的同一天?

例子:

   input                 Output

2018-07-25     ->       2018-06-25
2018-07-31     ->       2018-06-30 (because there is no 31)
Run Code Online (Sandbox Code Playgroud)

我的代码

$d = "2018-07-25";
$xd = date_parse_from_format("y-m-d", $d last month);
$output_d = date_create($xd)->format('Y-m-d');
Run Code Online (Sandbox Code Playgroud)

Joh*_*nde 6

<?php
$date = new DateTimeImmutable("2018-07-31");
$previous = $date->sub(new DateInterval('P1M'));
$lastMonth= $date->modify('last day of previous month');
if ($previous > $lastMonth) {
    $previous = $lastMonth;
}
echo $previous ->format('Y-m-d');
Run Code Online (Sandbox Code Playgroud)

此代码从当前日期减去一个月。如果它大于上个月的最后一天,我们将使用上个月的最后一天。

演示