php 如何在不跳过的情况下在日期上添加 1 个月,即 2 月

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10724305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:53:57  来源:igfitidea点击:

How to add 1 month on a date without skipping i.e. february

phpdatetime

提问by Kasihasi

Possible Duplicate:
PHP DateTime::modify adding and subtracting months

可能重复:
PHP DateTime::modify 加减月份

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

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

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

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

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

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

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

  • If I add 1 month it will just add 1 on the month part and leave the day part (2011-01-15 will become 2011-02-15)
  • If the day is not existing in the month we will end, we take the last existing day of it (2011-01-30 will become 2011-02-28)
  • 如果我加 1 个月,它只会在月份部分加 1 并离开日期部分(2011-01-15 将变成 2011-02-15)
  • 如果这一天在我们将要结束的月份中不存在,我们取它的最后一天(2011-01-30 将变成 2011-02-28)

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!?

php 中是否有一个通用函数可以做到这一点,还是我必须自己编写代码?也许我只是缺少一个参数什么的!?

采纳答案by Kasihasi

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.

好像没有现成的函数,就自己写了。这应该可以解决我的问题。无论如何,感谢您的回答和评论。如果您发现一些错误,请在评论中提供。

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

回答by paulsm4

You have several alternatives besides DateInterval.

除了 DateInterval 之外,您还有多种选择。

Here are examples that use strtotime():

以下是使用的示例strtotime()

http://www.brightcherry.co.uk/scribbles/php-adding-and-subtracting-dates/

http://www.brightcherry.co.uk/scribbles/php-adding-and-subtracting-dates/

// Subtracting days from a date
$date = "1998-08-14";
$newdate = strtotime ( '-3 day' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-j' , $newdate );

echo $newdate;

...

...

// Subtracting months from a date
$date = "1998-08-14";
$newdate = strtotime ( '-3 month' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-j' , $newdate );

echo $newdate;

Here's are some links for DateInterval:

以下是一些链接DateInterval

Q: Exactly how doyou define a "month"?

问:究竟怎么,你定义一个“月”?

Def#1): a "month" is a "month" - regardless of #/days

Def#2): a "month" is 30 days (for example)

Def#3): a "month" is the #/days between the 1st Monday of subsequent months

etc. etc

定义#1):“月”就是“月”——不管#/days

定义#2):“月”是 30 天(例如)

定义#3):“月”是随后几个月的第一个星期一之间的#/天

等等等等

Q: What exactly is your "definition"?

问:你的“定义”究竟是什么?

回答by paulsm4

OK - as far as I can tell, you still haven't clearly defined what you mean by "month".

好的 - 据我所知,您仍然没有明确定义“月”的含义。

But here's one more function that might help:

但这里还有一个可能有帮助的功能:

http://php.net/manual/en/function.getdate.php

http://php.net/manual/en/function.getdate.php

/* Function to find the first and last day of the month from the given date.
*
* Author Binu v Pillai            [email protected]
* @Param            String             yyyy-mm-dd
*
*/
function findFirstAndLastDay($anyDate)
{
    //$anyDate            =    '2009-08-25';    // date format should be yyyy-mm-dd
    list($yr,$mn,$dt)    =    split('-',$anyDate);    // separate year, month and date
    $timeStamp            =    mktime(0,0,0,$mn,1,$yr);    //Create time stamp of the first day from the give date.
    $firstDay            =     date('D',$timeStamp);    //get first day of the given month
    list($y,$m,$t)        =     split('-',date('Y-m-t',$timeStamp)); //Find the last date of the month and separating it
    $lastDayTimeStamp    =    mktime(0,0,0,$m,$t,$y);//create time stamp of the last date of the give month
    $lastDay            =    date('D',$lastDayTimeStamp);// Find last day of the month
    $arrDay                =    array("$firstDay","$lastDay"); // return the result in an array format.

    return $arrDay;
}