从一个日期去除一个月 [英] Removing exactly one month from a date

查看:145
本文介绍了从一个日期去除一个月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您需要可靠且准确的日期操作,您似乎无法使用 strotime 。例如,如果这个月有31天,那么似乎 strtotime 只需要减少30天,而不是整个月。

It seems that you can't use strotime if you need reliable and accurate date manipulation. For example, if the month has 31 days, then it appears that strtotime simply minuses 30 days, not a whole month.

所以,例如,如果 $ event [EndDate] 等于2013-10-31 00:00:01,则代码如下: / p>

So, for example, if $event["EndDate"] is equal to "2013-10-31 00:00:01", the following code:

echo date("Y/n/j", strtotime('-1 month', strtotime($event["EndDate"]));

Ouputs: 2013/10/1 而不是 2013/09/30

Ouputs: 2013/10/1 instead of 2013/09/30.

QUESTION:现在如何我知道如何做不到,还有另一个更准确的方法是使PHP减去(或添加)一整个月,而不只是30天?

QUESTION: Now how I know how NOT to do it, is there another, more accurate, way to make PHP subtract (or add) exactly a whole month, and not just 30 days?

推荐答案

主要问题是 2013/09/31 不存在,所以更好的方法是使用第一天最后一天

The main issue is that 2013/09/31 does not exist so a better approach would be to use first day or last day of the previous month.

$date = new DateTime("2013-10-31 00:00:01");
$date->modify("last day last month");
echo $date->format("Y/n/j"); // 2013/9/30

当日期是 2013-10-15

$date = new DateTime("2013-10-15 00:00:01");
$day = $date->format("d");
$year = $date->format("Y");

$date->modify("last day last month");
$month = $date->format("m");

if (checkdate($month, $day, $year)) {
    $date->setDate($year, $month, $day);
}

echo $date->format("Y/n/j"); // 2013-9-15

这篇关于从一个日期去除一个月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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