Converting string to Date and DateTime

后端 未结 10 1651
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 17:07

If I have a PHP string in the format of mm-dd-YYYY (for example, 10-16-2003), how do I properly convert that to a Date and then a DateTime

10条回答
  •  遇见更好的自我
    2020-11-22 17:31

    To parse the date, you should use: DateTime::createFromFormat();

    Ex:

    $dateDE = "16/10/2013";
    $dateUS = \DateTime::createFromFormat("d.m.Y", $dateDE)->format("m/d/Y");
    

    However, careful, because this will crash with:

    PHP Fatal error: Call to a member function format() on a non-object 
    

    You actually need to check that the formatting went fine, first:

    $dateDE = "16/10/2013";
    $dateObj = \DateTime::createFromFormat("d.m.Y", $dateDE);
    if (!$dateObj)
    {
        throw new \UnexpectedValueException("Could not parse the date: $date");
    }
    $dateUS = $dateObj->format("m/d/Y");
    

    Now instead of crashing, you will get an exception, which you can catch, propagate, etc.

    $dateDE has the wrong format, it should be "16.10.2013";

提交回复
热议问题