簡體   English   中英

獲取月份的最后日期錯誤

[英]get last date in month error

我有以下代碼,該代碼獲取解析的日期,減去1個月。 這很完美。

$date = '22-05-2016';
print(date("Y-m-d 23:59:59", strtotime($date.' -1 months')));
// outputs 2016-04-22 23:59:59

有時我需要將日期強制為月底。 為此,我使用Ymt而不是Ymd它可以很好地工作。

$date = '22-05-2016';
print(date("Y-m-t 23:59:59", strtotime($date.' -1 months')));
// outputs 2016-04-30 23:59:59


問題是當解析的日期實際上是該月的最后一天時。 然后翻轉到下個月結束。

 $date = '31-05-2016'; print(date("Ymt 23:59:59", strtotime($date.' -1 months'))); 

實際輸出2016-05-31 23:59:59 (1個月未移除)

期望的輸出2016-04-30 23:59:59

編輯: 小提琴示例http://ideone.com/0fqlor

嘗試:

 $date = '31-05-2016';
 print(date("Y-m-d 23:59:59", strtotime($date.'  last day of last month')));

並探討strtotime可能性;)

在這里看看: http : //php.net/manual/en/datetime.formats.relative.php

最后注意事項: -1 month只能恢復30天。 因此,它將無法正常工作。 我認為有些PHP的東西;)

strtotime是您的朋友。 可以使用last day of May 2015last day of May 2015的語言字符串來檢索任何“給定”月份的last day of May 2015 -因此,為了方便輸入(猜測您使用日期選擇器而不是月份選擇器),請將所選日期轉換為其月份表達式第一:

date_default_timezone_set('Europe/London');
$to = '31-05-2016';
$month = date("M Y", strtotime($to));
$strtotime_expression = "last day of " . $month;
echo $strtotime_expression.": <br />";
print(date("Y-m-t 23:59:59", strtotime($strtotime_expression)));

http://ideone.com/YvjVeP

暫無
暫無

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

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