gpt4 book ai didi

PHP Carbon DateTime 增加两个月并完全跳过 11 月

转载 作者:行者123 更新时间:2023-12-02 15:04:59 25 4
gpt4 key购买 nike

我需要显示三个日历,一个用于当前月份,另外两个用于接下来的两个月。

我正在使用 Carbon 进行这些计算。

今天是 10 月 31 日。

如果我写下以下内容

$carbon = Carbon::now('UTC'); // current datetime in UTC is 8:54 AM October 31, 2016
echo $carbon->format('F') . '<br>';
echo $carbon->addMonths(1)->format('F');

我得到这个输出

October

December

我完全错过了 11 月...那么我如何在 10 月上添加一个月,以便得到 11 月。

最佳答案

默认情况下,addMonths(1) 为一个月精确添加 30 天。

要精确添加一个月(例如,从 10 月到 11 月,无论是 29/30/31 天),您需要取消 addMonth() 并改为使用 addMonthsNoOverflow(n).

例如:

$carbon = Carbon::now('UTC'); // current datetime in UTC is 8:54 AM October 31, 2016
echo $carbon->format('F') . '<br>';
echo $carbon->addMonths(1)->format('F');

意外的输出:

十月十二月

鉴于

$carbon = Carbon::now('UTC'); // current datetime in UTC is 8:54 AM October 31, 2016
echo $carbon->format('F') . '<br>';
echo $carbon->addMonthsNoOverflow(1)->format('F');

正确输出:

十月十一月

此行为不是由 Carbon 引起的,而是由其构建的 PHP 日期时间类引起的。

addMonthsNoOverflow() 不是默认行为的原因是因为这将是一个“重大更改”。

您可以在这个 Github 对话中了解更多相关信息:https://github.com/briannesbitt/Carbon/issues/627

关于PHP Carbon DateTime 增加两个月并完全跳过 11 月,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40339101/

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