PHP strtotime() different results of monday this week

廉价感情. 提交于 2019-12-06 22:20:41

问题


I have a problem getting the date of monday in the current week.

echo date('Y-m-d',strtotime('monday this week'));

When I'm running the above code on my local machine (PHP 5.3) it outputs correctly '2011-03-07', but the same code on my server (PHP 5.2) outputs '2011-03-14' (that's monday next week).

I've tried to run date('W') on both machines and I get the same result (10).

Edit: Any ideas how get this work correctly?

Thanks in advance.


回答1:


Not that I've seen exactly this problem, but I've seen ones very similar. strtotime seems to change behaviour between different versions of PHP, and barring the simple operations (eg. '+1 week'), it's difficult to guarantee that functionality will remain the same.

If you're not able to upgrade to 5.3, which as correctly pointed out does seem to be an improvement, all I can recommend, is playing with some permutations. It's often possible to get the right answer out of older versions of strtotime by rephrasing the question. Examples might include ...

  • next monday -1 week
  • last monday +1 week
  • this monday



回答2:


Use date('Y-m-d',strtotime(date('o-\\WW')));




回答3:


Yes, interpretation of strings in strtotime improved significantly in 5.3.




回答4:


Run the command "date" from the cli prompt on the server and your local desktop. This will verify if the OS is seeing the same date on both systems.




回答5:


You have two choices: either avoid using this function of check if the date is in the future, if yes you decement it by 7 days. Welcome to the wolderful world of PHP.




回答6:


Look at this:

"Be aware that you cannot rely on this function alone to validate a date, as it will accept insane dates like the 31st of February.

Also, the '... week' functionality by itself may not do what you expect. If used on a Sunday, 'next week' will not return a timestamp of the next Monday, but of the Monday after that. Similarly, a timestamp for the Monday of the current week is returned when 'previous/last week' is used and 'this week' returns a stamp of the Monday of the next week (i.e. the following day). This is not the 'week starts on Sunday' effect, as that would mean all the timestamps returned would have to be on a Sunday and none of them are."

Ff today is sunday, you will be wrong.




回答7:


Here is another solution that works (actually the only one that worked for me):

$mondayOfWeek = date ('d M Y', strtotime($someDate) - ((date ('N', strtotime($someDate)) - 1) * 3600 * 24));


来源:https://stackoverflow.com/questions/5247881/php-strtotime-different-results-of-monday-this-week

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