Strtotime() doesn't work with dd/mm/YYYY format
Here is the simplified solution:
$date = '25/05/2010';
$date = str_replace('/', '-', $date);
echo date('Y-m-d', strtotime($date));
Result:
2010-05-25
The strtotime
documentation reads:
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.
You can parse dates from a custom format (as of PHP 5.3) with DateTime::createFromFormat
$timestamp = DateTime::createFromFormat('!d/m/Y', '23/05/2010')->getTimestamp();
(Aside: The !
is used to reset non-specified values to the Unix timestamp, ie. the time will be midnight.)
If you do not want to (or cannot) use PHP 5.3, then a full list of available date/time formats which strtotime accepts is listed on the Date Formats manual page. That page more thoroughly describes the fact that m/d/Y
is inferred over d/m/Y
(but you can, as mentioned in the answers here, use d-m-Y
, d.m.Y
or d\tm\tY
).
In the past, I've also resorted to the quicky str_replace
mentioned in another answer, as well as self-parsing the date string into another format like
$subject = '23/05/2010';
$formatted = vsprintf('%3$04d/%2$02d/%1$02d', sscanf($subject,'%02d/%02d/%04d'));
$timestamp = strtotime($formatted);
This is a good solution to many problems:
function datetotime ($date, $format = 'YYYY-MM-DD') {
if ($format == 'YYYY-MM-DD') list($year, $month, $day) = explode('-', $date);
if ($format == 'YYYY/MM/DD') list($year, $month, $day) = explode('/', $date);
if ($format == 'YYYY.MM.DD') list($year, $month, $day) = explode('.', $date);
if ($format == 'DD-MM-YYYY') list($day, $month, $year) = explode('-', $date);
if ($format == 'DD/MM/YYYY') list($day, $month, $year) = explode('/', $date);
if ($format == 'DD.MM.YYYY') list($day, $month, $year) = explode('.', $date);
if ($format == 'MM-DD-YYYY') list($month, $day, $year) = explode('-', $date);
if ($format == 'MM/DD/YYYY') list($month, $day, $year) = explode('/', $date);
if ($format == 'MM.DD.YYYY') list($month, $day, $year) = explode('.', $date);
return mktime(0, 0, 0, $month, $day, $year);
}