如何添加1个月的日期不跳过,即2月 [英] How to add 1 month on a date without skipping i.e. february

查看:106
本文介绍了如何添加1个月的日期不跳过,即2月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

PHP DateTime ::修改添加和减去月份

我有一个开始日期(即2011-01-30),并希望添加1个月。

I have a starting date (i.e. 2011-01-30) and want to add 1 month.

问题在于定义一个月份。所以如果我使用以下代码:

The problem is in defining what a month is. So if I use the following code:

$d1 = DateTime::createFromFormat('Y-m-d H:i:s', '2011-01-30 15:57:57');
$d1->add(new DateInterval('P1M'));
echo $d1->format('Y-m-d H:i:s');

我得到以下结果:2011-03-02 15:57:57

I get the following result: 2011-03-02 15:57:57

问题是,我需要使用以下规则:

The problem is, that I need it to use the following rules:


  • 如果我添加1月份只会在月份加1,离开日子部分
    (2011-01-15将成为2011-02-15)

  • 如果一天不存在在这个月我们会结束,我们拿最后一个现在的日子
    (2011-01-30将成为2011-02-28)

php中有一个常用的功能,可以做到这一点,还是自己编写代码?
也许我只是缺少一个参数或者什么东西!

Is there a common function in php that can do this or do I have to code it by myself? Maybe I'm just missing a parameter or something!?

推荐答案

似乎没有准备好的函数所以我自己写了。
这应该可以解决我的问题。感谢您的回答和意见。
如果您发现某些错误,请在评论中提供。

It seems that there is no ready function for it, so I wrote it by myself. This should solve my problem. Thanks anyway for your answers and comments. If you will find some errors, please provide in the comments.

此函数计算添加一个月后的月份和结束年份。然后它检查日期是否正确。如果没有,我们有一天这个日子不在目标月份,所以我们在这个月的最后一天。
通过PHP 5.3.10进行测试。

This function calculates the month and the year I will end in after adding some month. Then it checks if the date is right. If not, we have the case that the day is not in the target month, so we take the last day in the month instead. Tested with PHP 5.3.10.

<?php
$monthToAdd = 1;

$d1 = DateTime::createFromFormat('Y-m-d H:i:s', '2011-01-30 15:57:57');

$year = $d1->format('Y');
$month = $d1->format('n');
$day = $d1->format('d');

$year += floor($monthToAdd/12);
$monthToAdd = $monthToAdd%12;
$month += $monthToAdd;
if($month > 12) {
    $year ++;
    $month = $month % 12;
    if($month === 0)
        $month = 12;
}

if(!checkdate($month, $day, $year)) {
    $d2 = DateTime::createFromFormat('Y-n-j', $year.'-'.$month.'-1');
    $d2->modify('last day of');
}else {
    $d2 = DateTime::createFromFormat('Y-n-d', $year.'-'.$month.'-'.$day);
}
$d2->setTime($d1->format('H'), $d1->format('i'), $d1->format('s'));
echo $d2->format('Y-m-d H:i:s');

这篇关于如何添加1个月的日期不跳过,即2月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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