i am Roger Li

PHP strtotime() 出現不是預期的結果(昨天還正常哦!?)

小小PHP debug測驗,今天是31/5/2016,你應為以下這段PHP碼會得出甚麼結果呢?

<?php 
for($i=0; $i<12; $i++){ 
$my_date_year = date('Y', strtotime((-$i)." month")); 
$my_date_month = date('m', strtotime((-$i)." month"));
echo $my_date_year.$my_date_month; 
echo "<br/>"; } 
?> 

認為是A 還是B ?

A)
201605
201604
201603
201602
201601
201512
201511
201510
201509
201508
201507
201506

B)
201605
201605
201603
201603
201601
201512
201512
201510
201510
201508
201508
201506

答案是B 。
如果你應為是A,你和我一起中伏了。

解決方法是:

 <?php 
for($i=0; $i<12; $i++){ 
$my_date_year = date('Y', strtotime((-$i)." month",strtotime(date("F") . "1"))); 
$my_date_month = date('m', strtotime((-$i)." month",strtotime(date("F") . "1")));
echo $my_date_year.$my_date_month; 
echo "<br/>"; } 
?> 

我實太年輕了,今天才遇到這個問題。注意,這個不算是PHP strtotime()的bug呢,只是我這段script的bug。

為什麼? 有時間可參考: https://bugs.php.net/bug.php?id=22486&edit=2

[2003-03-01 09:32 UTC] [email protected]Well, we’ll have to agree to disagree. A month is a period of time just like a second, a minute and an hour. It is not as well-defined since it varies from one month to the next, but on the average it is 30.5 days. Without further context, if you simply say that something will take a month or you use 「a month」 without specifying which month, the only correct assumption to make is that it is a period of time approximately 30.5 days. This is exactly the same problem you have if you simply add a month to the mktime() month argument without changing the day. If you tell mktime to give you the unix timestamp for Feb. 30, it is going to give you the timestamp for March 2. If what you really want is the timestamp for the 1st day of the next month, simply get the current month and add 1 to it and feed it the day in the next month you want in your mktime call. eg. $t = mktime(12,0,0,date(『n』)+1,10,date(『Y』)); That will give you the timestame for noon on the 10th day of the next month in the current year. Any change to what a month is in the current strtotime() code is going to break a lot of applications as most people want and expect the current behaviour. And relax, I was just kidding with the example. I won’t actually show up and beat the crap out of you in a month.




發表回覆

你的電郵地址並不會被公開。 必要欄位標記為 *