如何将日期解析为上个月的同一天? [英] How can i parse a date to same day of previous month?

查看:187
本文介绍了如何将日期解析为上个月的同一天?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can i parse a date to same day of previous month in 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');


推荐答案

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

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

This code subtracts one month from the current date. If it is greater than the last day of the previous month we use the last day of the previous month instead.

演示

这篇关于如何将日期解析为上个月的同一天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆