PHP: strtotime returns “nothing” of type “boolean”

依然范特西╮ 提交于 2019-12-10 17:16:47

问题


I have the variable $EDate, I used strtotime function with this variable with different values and the result was as following:

$EDate = 10-21-2013;    echo "strtotime($EDate)";   the result = nothing    and the type is boolean
$EDate = 09-02-2013;    echo "strtotime($EDate)";   the result = 1360386000 and the type is integer
$EDate = 09-30-2013;    echo "strtotime($EDate)";   the result = nothing    and the type is boolean
$EDate = 09-30-2013;    echo "strtotime($EDate)";   the result = nothing    and the type is boolean
$EDate = 07-02-2014;    echo "strtotime($EDate)";   the result = 1391749200 and the type is integer
$EDate = 10-12-2014;    echo "strtotime($EDate)";   the result = 1418187600 and the type is integer

Can anybody explain this and how to avoid the boolean result?


回答1:


From the documentation:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

Your code assumes that the date is in d-m-y format, and will return FALSE since the month values are incorrect:

var_dump(strtotime('10-21-2013')); // no month 21
var_dump(strtotime('09-30-2013'));
var_dump(strtotime('09-30-2013'));

If you want to be able to use custom formats, use DateTime::createFromFormat() instead:

$date = DateTime::createFromFormat('m-d-Y', '10-21-2013');
echo $date->format('U');

Demo!




回答2:


Edit: This answer does not apply anymore to the question, see my comment below.

Put your values in quotes, so they become a string:

$EDate = '10-21-2013'; 
...

Your current code does a mathematical subtraction: 10 - 12 - 2013 = -2015.



来源:https://stackoverflow.com/questions/19164923/php-strtotime-returns-nothing-of-type-boolean

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