问题
PHP - DateTime::createFromFormat — Returns new DateTime object formatted according to the specified format
this works:
$var = DateTime::createFromFormat('Ymd','20100809')->getTimestamp();
but this fails with
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();
回答1:
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.
From the manual on createFromFormat:
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();
回答2:
It should be
DateTime::createFromFormat('Y/m/d H:i:s','2010/08/09 07:47:00')->getTimestamp()
^ ^
See date for the format used.
You could also use strtotime in this circumstance. This would give the same result:
strtotime('2010/08/09 07:47:00')
Another way:
date_create('2010/08/09 07:47:00')->getTimestamp()
Note that DateTime::createFromFormat returns FALSE on error. You can fetch the errors with DateTime::getLastErrors():
<?php
$d = DateTime::createFromFormat('Y/m/d H:M:S','2010/08/09 07:47:00');
var_dump($d);
var_dump(DateTime::getLastErrors());
would give:
bool(false)
array(4) {
["warning_count"]=>
int(0)
["warnings"]=>
array(0) {
}
["error_count"]=>
int(3)
["errors"]=>
array(1) {
[14]=>
string(13) "Trailing data"
}
}
回答3:
Use s in place of S and m in place of M
- s - Seconds, with leading zeros
- S - English ordinal suffix for the day of the month, 2 characters like st, nd, rd or th
and
- m - Numeric representation of a
month, with leading zeros - M - short textual representation of a month, three letters like Jan through Dec
回答4:
H:M:S M is month short name and S is ordinal (st, nd,rd,th) day of month try H:i:s
来源:https://stackoverflow.com/questions/3467315/datetimecreatefromformat-php-format-issue