[英]PHP Carbon DateTime adds two months and skips november entirely
我需要顯示三個日歷,其中一個用於當前月份,另外兩個則用於接下來的兩個月。
我正在使用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');
我得到這個輸出
十月
十二月
我完全想念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 datetime類。
addMonthsNoOverflow()
不是默認行為的原因是因為這將是“重大更改”。
您可以在此Github對話中了解更多有關它的信息: https : //github.com/briannesbitt/Carbon/issues/627
這是php基本庫中的錯誤: \\DateTime
在您的php啟動代碼集中:
Carbon:: useMonthsOverflow(false);
要解決此問題,只需使用addMonths()
。
警告,盡管這可能會破壞依賴Carbon的現有代碼(如果有)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.