Whenever you retrieve datetime from a table, the datetime gives ‘YYYY-MM-DD’ format. If you want to change the output, then you need to use in-built date_format() from MySQL.
The syntax is as follows −
SELECT DATE_FORMAT(yourDatetimeColumnName,yourFormat) as anyVariableName from yourTableName;
To understand the above syntax, let us first create a table. The query to create a table is as follows −
mysql> create table UserDateFormat -> ( -> ProductId int, -> ProductDeliverDate datetime -> ); Query OK, 0 rows affected (0.93 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into UserDateFormat values(100,date_add(now(),interval 1 year)); Query OK, 1 row affected (0.10 sec) mysql> insert into UserDateFormat values(101,date_add(now(),interval -1 year)); Query OK, 1 row affected (0.48 sec) mysql> insert into UserDateFormat values(102,date_add(now(),interval -3 year)); Query OK, 1 row affected (0.17 sec) mysql> insert into UserDateFormat values(103,date_add(now(),interval -2 year)); Query OK, 1 row affected (0.20 sec)
Display all records from the table using select command. The query is as follows −
mysql> select *from UserDateFormat;
Output
+-----------+---------------------+ | ProductId | ProductDeliverDate | +-----------+---------------------+ | 100 | 2019-12-24 13:32:47 | | 101 | 2017-12-24 13:32:58 | | 102 | 2015-12-24 13:33:08 | | 103 | 2016-12-24 13:33:17 | +-----------+---------------------+ 4 rows in set (0.00 sec)
The above datetime format is from MySQL datetime. Now you can format datetime accordingly, which includes the ‘DD-MM-YYYY’ format as well.
The query is as follows −
mysql> select date_format(ProductDeliverDate,'%d-%m-%Y %h:%i:%s') as UserFormat from UserDateFormat;
The following is the output displaying date in the DD-MM-YYYY format −
+----------------------+ | UserFormat | +----------------------+ | 24-12-2019 01:32:47 | | 24-12-2017 01:32:58 | | 24-12-2015 01:33:08 | | 24-12-2016 01:33:17 | +----------------------+ 4 rows in set (0.00 sec)
You can get the above time format in 24 hours. The query is as follows −
mysql> select date_format(ProductDeliverDate,'%d-%m-%Y %H:%i:%S') as UserFormat from UserDateFormat;
Output
+----------------------+ | UserFormat | +----------------------+ | 24-12-2019 13:32:47 | | 24-12-2017 13:32:58 | | 24-12-2015 13:33:08 | | 24-12-2016 13:33:17 | +----------------------+ 4 rows in set (0.00 sec)