gpt4 book ai didi

PHP:将月份添加到日期,但不超过该月的最后一天

转载 作者:IT王子 更新时间:2023-10-29 01:12:10 26 4
gpt4 key购买 nike

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

我需要在日期中加上月份数,但不能超过每月的最后一天。

例如:

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 中使用日期加法,我会超限:

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

我的规范不允许我超限到新的一个月。

完成此任务最简单的方法是什么?

最佳答案

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

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:将月份添加到日期,但不超过该月的最后一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5760262/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com