PHP Strtotime erratic function

隐身守侯 提交于 2019-12-11 04:33:01

问题


The following code should take the fourth friday of February and the fourth friday of April and return it.

$datei1 = date(strtotime('fourth friday', strtotime('february', strtotime(date('01-m-Y')))));

$datei2 = date(strtotime('fourth friday', strtotime('april', strtotime(date('01-m-Y')))));

Its working but taking the 5th friday of April not the fourth. I can only assume that it does not believe the first of April counts.

Any ideas,

Marvellous


回答1:


Your code is very complicated for no reason. Try this (PHP 5.3):

$date = date('Y-m-d', strtotime('fourth friday of april 2011'));

This will give you:

2011-04-22

In PHP 5.2, this syntax seems to work in all cases:

$date = date('Y-m-d', strtotime('fourth friday', strtotime('april - 1 second')));



回答2:


strtotime('fourth friday', $now) probably really means "the fourth Friday relative to $now".

The $now parameter you give is 1st April 2011, which is a Friday. The fourth Friday after Fri 1st April is the fifth Friday of the month.




回答3:


It appears you're using an older version of PHP. Major changes have been introduced to handle the edge case you're experiencing here. In which case I believe the following is the cleanest approach:

echo date('Y-m-d', strtotime('+4 fridays', mktime(0,0,0,4,0,date('Y'))));
// or
echo date('Y-m-d', strtotime('fourth friday', mktime(0,0,0,4,0,date('Y'))));

This should give you the fourth friday in april of the current year. I've tested successfully in 5.3 but you'll have to test on you older installation.




回答4:


PHP Changelog ::

5.2.7 In PHP 5 prior to 5.2.7, requesting a given occurrence of a given weekday in a month where that weekday was the first day of the month would incorrectly add one week to the returned timestamp. This has been corrected in 5.2.7 and later versions.



来源:https://stackoverflow.com/questions/5486949/php-strtotime-erratic-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!