Reputation: 641
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();
Upvotes: 12
Views: 28032
Reputation: 97835
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" } }
Upvotes: 11
Reputation: 449595
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();
Upvotes: 19
Reputation: 212452
H:M:S M is month short name and S is ordinal (st, nd,rd,th) day of month try H:i:s
Upvotes: 0
Reputation: 455262
Use s in place of S and m in place of M
and
Upvotes: 0