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