It's very easy just use DateTime::createFromFormat()
$date = DateTime::createFromFormat('d/m/Y', '21/07/2014');
echo $date->format('Y-m-d');
See the live demo on eval.in
For enhancement
You can then also check against invalid input if you extend the snippet above a bit:
if(($date = DateTime::createFromFormat('d/m/Y', '21//2014')) !== false)
echo $date->format('Y-m-d');
else
echo 'Invalid format';
But this is only a pattern check which is similar to a regex like
/(\d{1,2})/(\d{1,2})/(\d{4})/
This still allows the user to enter something like:
50/13/2014
To check wether the provided date is valid or invalid check the content of DateTime::getLastErrors(). It will tell you in detail what went wrong. For the example above you'll get something like this:
array(4) {
["warning_count"]=>
int(1)
["warnings"]=>
array(1) {
[10]=>
string(27) "The parsed date was invalid"
}
["error_count"]=>
int(0)
["errors"]=>
array(0) {
}
}
So according to this information we can extend the snippet again a bit. Which leads us to a result similar like this:
$date = DateTime::createFromFormat('d/m/Y', '50/13/2014')
if($date !== false) {
$dateLastErrors = $date->getLastErrors();
if($dateLastErrors['error_count'] > 0 || $dateLastErrors['warning_count'] > 0)
echo 'Invalid date';
else
echo $date->format('Y-m-d');
} else
echo 'Invalid date format';
}
Which will finally check the date against format an validation.