I really like the strtotime()
function, but the user manual doesn\'t give a complete description of the supported date formats. strtotime(\'dd/mm/YYYY\')<
This workaround is simpler and more elegant than explode:
$my_date = str_replace("/", ".", $my_date);
$my_date = strtotime($my_date);
$my_date = date("Y-m-d", $my_date);
You don't have to know what format you're getting the date in, but if it comes with slashes they are replaced with full stops and it is treated as European by strtotime.
From the STRTOTIME writeup Note:
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.
It is as simple as that.
I haven't found a better solution. You can use explode()
, preg_match_all()
, etc.
I have a static helper function like this
class Date {
public static function ausStrToTime($str) {
$dateTokens = explode('/', $str);
return strtotime($dateTokens[1] . '/' . $dateTokens[0] . '/' . $dateTokens[2]);
}
}
There is probably a better name for that, but I use ausStrToTime()
because it works with Australian dates (which I often deal with, being an Australian). A better name would probably be the standardised name, but I'm not sure what that is.
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);
}
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.
fastest should probably be
false!== ($date !== $date=preg_replace(';[0-2]{2}/[0-2]{2}/[0-2]{2};','$3-$2-$1',$date))
this will return false if the format does not look like the proper one, but it wont-check wether the date is valid