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

How can i parse a date to same day of previous month?

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

示例:

   input                 Output

2018-07-25     ->       2018-06-25
2018-07-31     ->       2018-06-30 (because there is no 31)

我的代码

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

回到一个月就像从现有日期减去一个月,所以借助 strtotime 和 date 我们可以解决这个问题。喜欢,

$a = "2018-07-25"; $b = date("Y-m-d",strtotime($a."-1 month")); $b is 2018-06-25

希望对您有所帮助。

<?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');

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

Demo