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)
<?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)
此代码从当前日期减去一个月。如果它大于上个月的最后一天,我们将使用上个月的最后一天。
| 归档时间: |
|
| 查看次数: |
1047 次 |
| 最近记录: |