
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Format Date in MySQL Select Query Using FORMATDate Method
Use the DATE_FORMAT(), not FORMATDATE() in MySQL to format date. The correct syntax is as follows −
SE LECT *, DATE_FORMAT(yourDateCoumnName,’yourFormat’) as anyAliasName FROM yourTableName
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table DateFormatDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> UserName varchar(10), -> UserLoginDate date -> ); Query OK, 0 rows affected (0.94 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into DateFormatDemo(UserName,UserLoginDate) values('Mike',curdate()); Query OK, 1 row affected (0.21 sec) mysql> insert into DateFormatDemo(UserName,UserLoginDate) values('Sam','2018-05-09'); Query OK, 1 row affected (0.17 sec) mysql> insert into DateFormatDemo(UserName,UserLoginDate) values('Carol','2016-01-15'); Query OK, 1 row affected (0.17 sec) mysql> insert into DateFormatDemo(UserName,UserLoginDate) values('Bob','2015-12-31'); Query OK, 1 row affected (0.17 sec) mysql> insert into DateFormatDemo(UserName,UserLoginDate) values('David','2012-08-19'); 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 DateFormatDemo;
The following is the output −
+----+----------+---------------+ | Id | UserName | UserLoginDate | +----+----------+---------------+ | 1 | Mike | 2019-02-06 | | 2 | Sam | 2018-05-09 | | 3 | Carol | 2016-01-15 | | 4 | Bob | 2015-12-31 | | 5 | David | 2012-08-19 | +----+----------+---------------+ 5 rows in set (0.00 sec)
Let us format date using DATE_FORMAT() with SELECT *. The query is as follows −
mysql> select *,DATE_FORMAT(UserLoginDate,'%d-%m-%Y') as NewFormatOfDate from DateFormatDemo;
The following is the output −
+----+----------+---------------+-----------------+ | Id | UserName | UserLoginDate | NewFormatOfDate | +----+----------+---------------+-----------------+ | 1 | Mike | 2019-02-06 | 06-02-2019 | | 2 | Sam | 2018-05-09 | 09-05-2018 | | 3 | Carol | 2016-01-15 | 15-01-2016 | | 4 | Bob | 2015-12-31 | 31-12-2015 | | 5 | David | 2012-08-19 | 19-08-2012 | +----+----------+---------------+-----------------+ 5 rows in set (0.00 sec)
Advertisements