簡體   English   中英

php:strtotime(“12/31/2004 +6個月”)); 沒有回到六月的最后一天

[英]php: strtotime(“12/31/2004 +6 month”)); not returning the last day of June

我預計在功能回到6/30/2005 ,而不是7/1/2005

print date("m/d/Y", strtotime("12/31/2004 +6 month"));

同樣, print date("m/d/Y", strtotime("1/31/2011 +1 month"))返回03/03/2011同時希望它返回2/28/2011

有沒有人知道是否有一種直接的方式來顯示添加月份的最后一天?

這個怎么樣?

echo date("m/d/Y", strtotime("last day of 12/31/2004 + 6 month")); // 6/30/2005
echo date("m/d/Y", strtotime("last day of 1/31/2011 + 1 month")); // 2/28/2011

演示

編輯:供您參考,以下是相關時間文檔的鏈接。

如果沒有那個月的日子,那么strtotime會繼續到下個月,你可以回到6個月並檢查它是否在開始日期結束

  $date2 = date("Y-m-d", strtotime("{$date} +6 months"));
  $date3 = date("Y-m-d", strtotime("{$date2} -6 months"));
  if($date3 != $date)
  {
     $date2 = date("Y-m-t", strtotime("{$date2} -1 months"));
  }

(或在你的情況下“m / t / Y”)

一種簡單的方法是實際提前一個月,然后將值設為零。 此外,mktime()可能更容易

$mymonth = 2;   // I want the last day of February
echo date('m/d/Y', mktime(0,0,0,$mymonth+1,0,2011));

這應該會在2/28/2011返回。

strtotime利用相互沖突的信息盡力而為。

1/31/2011 +1month

意味着前進到

2/31/2011

但二月只有28天(有時是29天)。 2011年不是閏年,因此“二月31日”正常化為“3月3日”。

同樣適用於'12 / 31/2004 + 6個月'。 這將帶你到2005年6月31日。但是6月只有30天,所以日期標准化為7月1日。

暫無
暫無

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

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