Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime::createFromFormat - php format issue

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();
like image 651
roger rover Avatar asked Aug 12 '10 11:08

roger rover


2 Answers

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();
like image 191
Pekka Avatar answered Nov 06 '22 16:11

Pekka


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"
  }
}
like image 34
Artefacto Avatar answered Nov 06 '22 15:11

Artefacto