DateTime :: createFromFormat-PHP格式问题 [英] DateTime::createFromFormat - php format issue
问题描述
PHP-DateTime :: createFromFormat —返回根据指定格式设置的新DateTime对象
PHP - DateTime::createFromFormat — Returns new DateTime object formatted according to the specified format
这有效:
$var = DateTime::createFromFormat('Ymd','20100809')->getTimestamp();
但这失败
在非对象上调用成员函数getTimestamp()
Call to a member function getTimestamp() on a non-object
$var = DateTime::createFromFormat('Y/m/d H:M:S','2010/08/09 07:47:00')->getTimestamp();
推荐答案
在当前情况下,M:S
部分是错误的.它必须是i:s
.请参见 manual on date().
In the case at hand, the M:S
portion is wrong. It needs to be i:s
. See the manual on date().
但是,这突出了一个更深层的概念性问题:两个参数中的任何错误输入都将导致致命错误,这对于生产中的应用程序而言是不良行为.
However, this highlights a deeper conceptual problem: An incorrect input in either parameter will lead to a fatal error, which is bad behaviour for an application in production.
摘自 createFromFormat
上的手册:
From the manual on createFromFormat
:
失败时返回新的DateTime实例或FALSE.
Returns a new DateTime instance or FALSE on failure.
当呼叫无法根据您的输入建立日期时,将不会返回任何对象.
When the call fails to build a date from your input, no object is returned.
为避免输入错误而造成致命错误,您必须(不幸的是,因为这破坏了很好的链接),必须首先检查是否成功:
To avoid fatal errors on incorrect inputs, you would (sadly, as this breaks the nice chaining) have to check for success first:
$var = DateTime::createFromFormat('Y/m/d H:M:S','2010/08/09 07:47:00');
if ($var instanceof DateTime)
echo $var->getTimestamp();
这篇关于DateTime :: createFromFormat-PHP格式问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!