php date() 方法,“遇到格式不正确的数值”不想格式化 $_POST 中传递的日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20574465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
date() method, "A non well formed numeric value encountered" does not want to format a date passed in $_POST
提问by Prefix
I unfortunately can't use DateTime()as the server this project is on is running PHP v.5.2.
不幸的DateTime()是,我无法使用该项目所在的服务器正在运行 PHP v.5.2。
the line in question:
有问题的行:
$aptnDate2 = date('Y-m-d', $_POST['nextAppointmentDate']);
throws the following error:
引发以下错误:
Notice: A non well formed numeric value encountered
so I var dump to make sure it's well formatted..
所以我 var dump 以确保它的格式正确..
var_dump($_POST['nextAppointmentDate']);
string(10) "12-16-2013"
The php docs statethat it takes a timestamp not a string. but when I do:
在PHP的文档说明,它需要一个时间戳不是一个字符串。但是当我这样做时:
date('Y-m-d', strtotime($_POST['nextAppointmentDate']));
and then var_dumpthe result, I get this:
然后var_dump结果,我得到了这个:
string(10) "1969-12-31"
why can I not format a date with this date value and strtotime()?
为什么我不能用这个日期值和 strtotime() 格式化日期?
thanks!
谢谢!
回答by Amal Murali
From the documentation for strtotime():
从文档中strtotime():
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.
m/d/y 或 dmy 格式的日期通过查看各个组件之间的分隔符来消除歧义:如果分隔符是斜杠 (/),则假定为美国 m/d/y;而如果分隔符是破折号 (-) 或点 (.),则假定为欧洲 dmy 格式。
In your date string, you have 12-16-2013. 16isn't a valid month, and hence strtotime()returns false.
在您的日期字符串中,您有12-16-2013. 16不是有效月份,因此strtotime()返回false.
Since you can't use DateTime class, you could manually replace the -with /using str_replace()to convert the date string into a format that strtotime()understands:
由于您不能使用 DateTime 类,您可以手动替换-with /usingstr_replace()将日期字符串转换为strtotime()可理解的格式:
$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16

