Created
July 6, 2011 10:35
-
-
Save jotbe/1066973 to your computer and use it in GitHub Desktop.
MySQL: Get formatted ISO date from string with european date (can be easily extended to other formats)
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
/** | |
* This script has been tested in MySQL 5.1.37. | |
* It might work with other SQL-DBMS as well. | |
*/ | |
DROP FUNCTION IF EXISTS getSqlDate; | |
DELIMITER // | |
CREATE FUNCTION getSqlDate(str VARCHAR(10)) | |
RETURNS VARCHAR(10) DETERMINISTIC | |
CASE | |
WHEN (str REGEXP '^[0-3][0-9]\.[01][0-9]\.[0-9]{4}$') THEN | |
/* European: 01.06.2011 */ | |
RETURN STR_TO_DATE(str, GET_FORMAT(DATE, 'EUR')); | |
WHEN (str REGEXP '^[0-9]{4}-[01][0-9]-[0-3][0-9]$') THEN | |
/* ISO 8601: 2011-06-01 */ | |
RETURN str; | |
ELSE | |
RETURN 'ERR'; | |
END CASE; | |
// | |
DELIMITER ; | |
SELECT | |
@eur := '01.01.2011' eur_date, | |
@iso := '2011-01-01' iso_date, | |
STR_TO_DATE(@eur, GET_FORMAT(DATE, 'EUR')) eur_str2date, | |
STR_TO_DATE(@iso, GET_FORMAT(DATE, 'ISO')) iso_str2date, | |
(@eur REGEXP '^[0-3][0-9]\.[01][0-9]\.20[0-9]{2}$') eur_valid_date, | |
(@iso REGEXP '^20[0-9]{2}-[01][0-9]-[0-3][0-9]$') iso_valid_date, | |
@date := @eur test_date, | |
getSqlDate(@date) test_date_out; | |
/** | |
* Output: | |
* +------------+------------+--------------+--------------+----------------+----------------+------------+---------------+ | |
* | eur_date | iso_date | eur_str2date | iso_str2date | eur_valid_date | iso_valid_date | test_date | test_date_out | | |
* +------------+------------+--------------+--------------+----------------+----------------+------------+---------------+ | |
* | 01.01.2011 | 2011-01-01 | 2011-01-01 | 2011-01-01 | 1 | 1 | 01.01.2011 | 2011-01-01 | | |
* +------------+------------+--------------+--------------+----------------+----------------+------------+---------------+ | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I agree with you. The code is written and tested in MySQL - thanks for asking. I've just added the info to the gist.