mysql string to date code example

Example 1: cast string to datetime mysql

SELECT STR_TO_DATE('2017-03-13T14:39:01.123','%Y-%m-%dT%H:%i:%s.%f');

Example 2: sql to date

-- Oracle:TO_DATE(string, format)
SELECT TO_DATE('2012-06-05', 'YYYY-MM-DD') FROM dual;
SELECT TO_DATE('05/06/2012 13:25:12', 'DD/MM/YYYY HH24:MI:SS') FROM dual;
-- SQL Server: CONVERT(data_type, string, style). Cf source link for style codes.
SELECT CONVERT(DATETIME, '2012-06-05', 102);		-- Raises error if impossible
SELECT TRY_CONVERT(DATETIME, '2012-06-05', 102);	-- Returns Null if impossible
-- MySQL: STR_TO_DATE(string, format): 
SELECT STR_TO_DATE('2012-06-05','%Y-%m,%d');

Example 3: select STR_TO_DATE(date_seance1,'DD-MM-YYYY')

ORDER BY STR_TO_DATE(datestring, '%d/%m/%Y')

Example 4: DATE_FORMAT(STR_TO_DATE

mysql> Select STR_TO_DATE('22.10.2017',GET_FORMAT(DATE,'EUR'))AS 'EUROPEAN FORMAT';
+-----------------+
| EUROPEAN FORMAT |
+-----------------+
| 2017-10-22      |
+-----------------+
1 row in set (0.00 sec)

Example 5: DATE_FORMAT(STR_TO_DATE

mysql> Select * from date_testing1;
+-------+------------+
| Name | Date        |
+-------+------------+
| Ram   | 2017-05-03 |
| Shyam | 2003-10-31 |
+-------+------------+
2 rows in set (0.07 sec)

mysql> Select Name, Date, DATE_FORMAT(date,GET_FORMAT(date,'USA'))AS 'DATE IN US FORMAT'from date_testing1 Where Name='Ram';
+------+------------+-------------------+
| Name | Date       | DATE IN US FORMAT |
+------+------------+-------------------+
| Ram | 2017-05-03  | 05.03.2017        |
+------+------------+-------------------+
1 row in set (0.00 sec)

Tags:

Sql Example