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
For first Date
$_firstDate = date("m-d-Y", strtotime($_yourDateString));
For New Date
$_newDate = date("Y-m-d",strtotime($_yourDateString));
$d = new DateTime('10-16-2003');
$timestamp = $d->getTimestamp(); // Unix timestamp
$formatted_date = $d->format('Y-m-d'); // 2003-10-16
Edit: you can also pass a DateTimeZone to DateTime() constructor to ensure the creation of the date for the desired time zone, not the server default one.
Use strtotime()
on your first date then date('Y-m-d')
to convert it back:
$time = strtotime('10/16/2003');
$newformat = date('Y-m-d',$time);
echo $newformat;
// 2003-10-16
Make note that there is a difference between using forward slash /
and hyphen -
in the strtotime() function. To quote from php.net:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
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";
Like we have date "07/May/2018" and we need date "2018-05-07" as mysql compatible
if (!empty($date)) {
$timestamp = strtotime($date);
if ($timestamp === FALSE) {
$timestamp = strtotime(str_replace('/', '-', $date));
}
$date = date('Y-m-d', $timestamp);
}
It works for me. enjoy :)
You need to be careful with m/d/Y and m-d-Y formats. PHP considers /
to mean m/d/Y and -
to mean d-m-Y. I would explicitly describe the input format in this case:
$ymd = DateTime::createFromFormat('m-d-Y', '10-16-2003')->format('Y-m-d');
That way you are not at the whims of a certain interpretation.