How to create DateTime object from string in symfony2/php

55,709

Solution 1

I always create a DateTime object with its constructor, in your case it would be:

$protocol->setStartedAt(new \DateTime($post['started_at']));

if this works but does not use the timestamp posted you probably do not have the value in $post['started_at']. Try debugging it or just do the dirty trick:

die($post['started_at']);

Solution 2

For the sake of future readers who surely will someday encounter this problem (this is the first post if you google "symfony 2 datetime from string"), keep in mind that in Symfony 2 the DateTime object does NOT accept a string with that format : "d/m/Y H:i:s", and probably doesn't support many others either.

For the sake of not becoming mad at that, I've actually found out that the easiest and safest solution to avoid such errors is this one:

First, get your date string from whatever kind of request you are doing (In my case a generic AJAX request) and convert it to a DateTime Object, this example assumes that we need to create a dateTime object for 25/04/2015 15:00, which is the format of the jQuery UI italian DateTimePicker (that's just an example):

$literalTime    =   \DateTime::createFromFormat("d/m/Y H:i","25/04/2015 15:00");

(note: use \ to use php's DateTime object, else you will be using Symfony's datetime object that will throw you an exception)

Then, once you did it, create a date string using the comfort format function, by giving to the first parameter the output format expected (Y-m-d H:i:s):

$expire_date =  $literalTime->format("Y-m-d H:i:s");

In this way you are 100% sure that whatever kind of format you are passing or receiving this will properly be converted and you won't get any kind of exception from the DateTime symfony object, as long as you provide what you are expecting as an input.

Knowing that this post is actually quite old, I've just decided to post that because I didn't find any other valuable source but this one to understand where the problem could have been.

Please note that the best solution is still to send the datetime string in the correct format already, but if you literally have no ways to do that the safest way to convert such a string is the one above.

Solution 3

How about createFromFormat?

http://uk.php.net/manual/en/datetime.createfromformat.php

$from = DateTime::createFromFormat($post['started_at'], 'Y-m-d H:i:s');
Share:
55,709
DarkLeafyGreen
Author by

DarkLeafyGreen

Tackling Complexity in the Heart of Software

Updated on March 29, 2021

Comments

  • DarkLeafyGreen
    DarkLeafyGreen about 3 years

    In a DB table I have several fields with datetime as field type. So I need to persist data only as date time object.

    From a form I get date time as string like

    2012-10-05 17:45:54
    

    Now when ever I persist my entity I get following error:

    Fatal error: Call to a member function format() on a non-object in ..\DateTimeType.php on line 44

    I tried with

    $protocol->setStartedAt(strtotime($post['started_at']));
    

    or

    $from = \DateTime::createFromFormat('yy-mm-dd hh:mm:ss', $post['started_at']);
    $protocol->setStartedAt($from);
    

    or just

    $from = new \DateTime($post['started_at']);
    $protocol->setStartedAt($from);
    

    The last code works but it does not uses the timestamp passed as arguement but just gets the current time.

    Any ideas?

  • watermanio
    watermanio over 11 years
    Sorry, just seen you already have this - it's not working as the format looks incorrect. Try using the linked page to match up your format exactly - it's in PHP's format, not the weird Symfony one...
  • DarkLeafyGreen
    DarkLeafyGreen over 11 years
    Nope, still get this error, Call to a member function format() on a non-object DateTimeType.php line 44
  • nuala
    nuala over 9 years
    More debugging: var_dump the result of new DateTime() and if it's false use var_dump(\DateTime::getLastErrors()) for more details. php.net/manual/en/datetime.getlasterrors.php
  • desloovere_j
    desloovere_j about 8 years
    The solution above is false. Correct solution = $from = \DateTime::createFromFormat('Y-m-d H:i:s', $post['started_at']);
  • meles
    meles about 7 years
    Why the backslash? So symfony doesn't interprete it?
  • Laurynas Mališauskas
    Laurynas Mališauskas about 7 years
    You can add the DateTime with a use statement, then backslash will not be needed. Otherwise you have to declare full path to the class, in this case it is in default namespace so only backslash was needed.