PHP:向日期添加月份,但不超过该月的最后一天 [英] PHP: Adding months to a date, while not exceeding the last day of the month

查看:26
本文介绍了PHP:向日期添加月份,但不超过该月的最后一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望创建一个可以在 PHP 中执行此操作的函数.

Looking to create a function that will do this in PHP.

我需要给一个日期加上几个月,但不能超过每月的最后一天这样做.

I need to add a number of months to a date, but not exceed the last day of the month in doing so.

例如:

Add 1 month to January (1-28th), 2011, should produce February (1-28th), 2011.
Add 1 month to January 30th, 2011, should produce February 28th, 2011.
Add 3 months to January 31st, 2011, should produce April 30th, 2011.
Add 13 months to January 30th, 2011, should produce February 29th, 2012.
Add 1 month to October 31st, 2011, should produce November 30th, 2011.

如果我在 PHP 中使用日期添加,我会超支:

If I use date addition in PHP, I get overruns:

Adding 1 month to January 30th, 2011, results in March 2nd, 2011.

我的规范不允许我超支进入新的一个月.

My specification doesn't allow me to overrun into a new month.

实现此目的最简单的方法是什么?

What's the easiest method to accomplish this?

推荐答案

您可以比较添加 1 个月之前和之后的月份日期.如果不一样,下个月你就超过了.

You can compare the day of the month before and after you add 1 month. If it's not the same, you exceeded the next month.

function add($date_str, $months)
{
    $date = new DateTime($date_str);

    // We extract the day of the month as $start_day
    $start_day = $date->format('j');

    // We add 1 month to the given date
    $date->modify("+{$months} month");

    // We extract the day of the month again so we can compare
    $end_day = $date->format('j');

    if ($start_day != $end_day)
    {
        // The day of the month isn't the same anymore, so we correct the date
        $date->modify('last day of last month');
    }

    return $date;
}

$result = add('2011-01-28', 1);   // 2011-02-28
$result = add('2011-01-31', 3);   // 2011-04-30
$result = add('2011-01-30', 13);  // 2012-02-29
$result = add('2011-10-31', 1);   // 2011-11-30
$result = add('2011-12-30', 1);   // 2011-02-28

这篇关于PHP:向日期添加月份,但不超过该月的最后一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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