Last active
August 23, 2017 20:10
-
-
Save imelgrat/12db9117c542417431d6 to your computer and use it in GitHub Desktop.
A PHP function to detect and convert dates from different formats into a MySQL-compatible format (YYYY-MM-DD). Full article at: http://imelgrat.me/php/date-formatting-detect-convert/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @author Ivan Ariel Melgrati | |
* @copyright 2015 | |
*/ | |
function convert_date_format($old_date = '') | |
{ | |
$old_date = trim($old_date); | |
if (preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/', $old_date)) // MySQL-compatible YYYY-MM-DD format | |
{ | |
$new_date = $old_date; | |
} | |
elseif (preg_match('/^(0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-[0-9]{4}$/', $old_date)) // DD-MM-YYYY format | |
{ | |
$new_date = substr($old_date, 6, 4) . '-' . substr($old_date, 3, 2) . '-' . substr($old_date, 0, 2); | |
} | |
elseif (preg_match('/^(0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-[0-9]{2}$/', $old_date)) // DD-MM-YY format | |
{ | |
$new_date = substr($old_date, 6, 4) . '-' . substr($old_date, 3, 2) . '-20' . substr($old_date, 0, 2); | |
} | |
else // Any other format. Set it as an empty date. | |
{ | |
$new_date = '0000-00-00'; | |
} | |
return $new_date; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment