簡體   English   中英

PHP Date函數跳過二月。 有人知道這個日期錯誤的解決方法嗎?

[英]PHP Date function skipping February. Does anybody know of a work around for this date bug?

我要顯示未來三個月的月份標題,以及每個月的第一天和最后一天。

for($i = 1; $i < 4; $i++) { // For each month for 3 months
    $monthTitle = date('F Y', strtotime('+'.$i.' month'));
    $begin_date = date('Y-m-01', strtotime('+'.$i.' month')); // First day of calendar month in future.
    $end_date = date('Y-m-t', strtotime('+'.$i.' month')); // Last day of calendar months in future.
};

2015年11月29日的輸出是:

December 2015
2015-12-01
2015-12-31
January 2016
2016-01-01
2016-01-31
February 2016
2016-02-01 
2016-02-29

直到2015年11月29日為止,這個工作一直很好,但是今天(2015年11月30日)則跳過了2月。

2015年11月30日的輸出是:

December 2015
2015-12-01
2015-12-31
January 2016
2016-01-01
2016-01-31
March 2016
2016-03-01 
2016-03-31

我正在猜測一個錯誤,但是有人知道可以解決嗎?

您可以使用DateInterval將一個月添加到當前日期,這樣就可以獲得月的第一天和最后一天。

<?php
$date = new DateTime('2015-12-01');
$i = 0;
while($i < 3){
    printf("%s | first day: %s, | last day: %s <br>", $date->format('F Y'), $date->format('d'), $date->format('t'));
    $date->add(new DateInterval('P1M'));
    $i++;
}

輸出:

December 2015 - first day: 01, | last day: 31
January 2016 - first day: 01, | last day: 31
February 2016 - first day: 01, | last day: 29 

感謝@devlin carnate為我指出正確的方向。

for($i = 1; $i < 4; $i++) { # for each month
    $tmp = date('Y-m-15'); // Get the middle of the month to avoid PHP date bug.
    $begin_date = date('Y-m-01', strtotime($tmp . '+'.$i.' month')); // First day of calendar month in future.
    $end_date = date('Y-m-t', strtotime($begin_date)); // Last day of calendar months in future.
    $monthTitle = date('F Y', strtotime($begin_date));
};

這似乎工作得很好。

如果需要下個月的最后一天,則可以使用

$d = new DateTime( '2010-01-31' );
$d->modify( 'last day of next month' );
echo $d->format( 'Y-m-d' ), "\n";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM