How to create DateTime object from string in symfony2/php

前端 未结 3 1812
南方客
南方客 2021-02-07 23:48

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 l

相关标签:
3条回答
  • 2021-02-08 00:12

    i always create DateTime object with its constructor, os 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 debuging it or just do the dirty trick:

    die($post['started_at']);
    
    0 讨论(0)
  • 2021-02-08 00:13

    How about createFromFormat?

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

    $from = DateTime::createFromFormat($post['started_at'], 'Y-m-d H:i:s');
    
    0 讨论(0)
  • 2021-02-08 00:21

    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.

    0 讨论(0)
提交回复
热议问题