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 the solution i'm using even if the leading zero are there.
<?php
$date = '05/05/2017';
$date = str_replace('/', '-', $date);
$date = date('Y-m-d', strtotime($date));
echo $date;
?>
If you know it's in dd/mm/YYYY, you can do:
$regex = '#([/d]{1,2})/([/d]{1,2})/([/d]{2,4})#';
$match = array();
if (preg_match($regex, $date, $match)) {
if (strlen($match[3]) == 2) {
$match[3] = '20' . $match[3];
}
return mktime(0, 0, 0, $match[2], $match[1], $match[3]);
}
return strtotime($date);
It will match dates in the form d/m/YY or dd/mm/YYYY (or any combination of the two)...
If you want to support more separators than just /, you can change the regex to:
$regex = '#([\d]{1,2})[/-]([\d]{1,2})[/-]([\d]{2,4})#';
And then add any characters you want into the [/-]
bit (Note, the - character needs to be last)
$srchDate = date_format(date_create_from_format('d/m/Y', $srchDate), 'Y/m/d');
This will work for you. You convert the String into a custom date format where you can specify to PHP what the original format of the String is that had been given to it. Now that it is a date format, you can convert it to PHP's default date format, which is the same that is used by MySQL.