12

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();

4 Answers 4

20

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Not m:s; i:s. m is for moth.
11

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"
  }
}

1 Comment

thanks for DateTime::getLastErrors(), really useful ..
0

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

Comments

0

H:M:S M is month short name and S is ordinal (st, nd,rd,th) day of month try H:i:s

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.