Create date from day, month, year fields in MySQL?



You can use in-built function STR_TO_DATE() from MySQL. The syntax is as follows −

SELECT STR_TO_DATE(CONCAT(yourYearColumName,'-',LPAD(yourMonthColumName,2,'00'),'-',LPAD(yourDayColumName,2,'00')), '%Y-%m-%d') 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 DateCreateDemo    −> (    −> `Day` varchar(2),    −> `Month` varchar(2),    −> `Year` varchar(4)    −> ); Query OK, 0 rows affected (1.68 sec)

Insert values for all fields using insert command. The query is as follows −

mysql> insert into DateCreateDemo values('15','12','2018'); Query OK, 1 row affected (0.09 sec) mysql> insert into DateCreateDemo values('10','11','2016'); Query OK, 1 row affected (0.37 sec) mysql> insert into DateCreateDemo values('12','6','2017'); Query OK, 1 row affected (0.12 sec) mysql> insert into DateCreateDemo values('9','8','2019'); Query OK, 1 row affected (0.17 sec) mysql> insert into DateCreateDemo values('10','5','2020'); Query OK, 1 row affected (0.09 sec)

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

mysql> select *from DateCreateDemo;

The following is the output −

+------+-------+------+ | Day  | Month | Year | +------+-------+------+ | 15   | 12    | 2018 | | 10   | 11    | 2016 | | 12   | 6     | 2017 | | 9    | 8    | 2019 | | 10   | 5     | 2020 | +------+-------+------+ 5 rows in set (0.00 sec)

Create a date using the above three fields which is ‘Day’,’Month’ and ‘Year’. The query is as follows −

mysql> select −> STR_TO_DATE(CONCAT(Year,'-',LPAD(Month,2,'00'),'-',LPAD(day,2,'00')), '%Y-%m-%d') as DateDemo from DateCreateDemo;

The following is the output −

+------------+ | DateDemo | +------------+ | 2018-12-15 | | 2016-11-10 | | 2017-06-12 | | 2019-08-09 | | 2020-05-10 | +------------+ 5 rows in set (0.06 sec)
Updated on: 2019-07-30T22:30:24+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements