MySQL date format to convert dd.mm.yy to YYYY-MM-DD?


Use STR_TO_DATE() method from MySQL to convert. The syntax is as follows wherein we are using format specifiers. The format specifiers begin with %.

SELECT STR_TO_DATE(yourDateColumnName,'%d.%m.%Y') as anyVariableName FROM yourTableName;

To understand the above syntax, let us create a table. The query to create a table is as follows.

mysql> create table ConvertIntoDateFormat
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> LoginDate varchar(30),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.47 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into ConvertIntoDateFormat(LoginDate) values('11.01.2019');
Query OK, 1 row affected (0.10 sec)

mysql> insert into ConvertIntoDateFormat(LoginDate) values('10.04.2017');
Query OK, 1 row affected (0.16 sec)

mysql> insert into ConvertIntoDateFormat(LoginDate) values('21.10.2016');
Query OK, 1 row affected (0.12 sec)

mysql> insert into ConvertIntoDateFormat(LoginDate) values('26.09.2018');
Query OK, 1 row affected (0.14 sec)

mysql> insert into ConvertIntoDateFormat(LoginDate) values('25.12.2012');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement. The query is as follows−

mysql> select *from ConvertIntoDateFormat;

The following is the output.

+----+------------+
| Id | LoginDate  |
+----+------------+
|  1 | 11.01.2019 |
|  2 | 10.04.2017 |
|  3 | 21.10.2016 |
|  4 | 26.09.2018 |
|  5 | 25.12.2012 |
+----+------------+
5 rows in set (0.00 sec)

The following is the query to format the date to YYYY-MM-DD.

mysql> select str_to_date(LoginDate,'%d.%m.%Y') as DateFormat from ConvertIntoDateFormat;

Here is the output.

+------------+
| DateFormat |
+------------+
| 2019-01-11 |
| 2017-04-10 |
| 2016-10-21 |
| 2018-09-26 |
| 2012-12-25 |
+------------+
5 rows in set (0.00 sec)

You can also use DATE_FORMAT() method for the same purpose. The query is as follows

mysql> select DATE_FORMAT(STR_TO_DATE(LoginDate,'%d.%m.%Y'), '%Y-%m-%d') as DateFormat from
   -> ConvertIntoDateFormat;

The following is the output−

+------------+
| DateFormat |
+------------+
| 2019-01-11 |
| 2017-04-10 |
| 2016-10-21 |
| 2018-09-26 |
| 2012-12-25 |
+------------+
5 rows in set (0.00 sec)

Updated on: 30-Jul-2019

16K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements