- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 to return MonthName and Year?
Use DATE_FORMAT() and set the specifiers to display only the MonthName and Year. Let us first create a table −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, AdmissionDate date ); Query OK, 0 rows affected (0.69 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable(AdmissionDate) values('2013-04-21'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable(AdmissionDate) values('2014-01-31'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable(AdmissionDate) values('2016-09-01'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(AdmissionDate) values('2018-12-12'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(AdmissionDate) values('2019-04-01'); Query OK, 1 row affected (0.15 sec)
Display records from the table using select command −
mysql> select *from DemoTable;
This will produce the following output −
+----+---------------+ | Id | AdmissionDate | +----+---------------+ | 1 | 2013-04-21 | | 2 | 2014-01-31 | | 3 | 2016-09-01 | | 4 | 2018-12-12 | | 5 | 2019-04-01 | +----+---------------+ 5 rows in set (0.00 sec)
Here is the query to format date in MySQL to return MonthName and Year −
mysql> select DATE_FORMAT(AdmissionDate,'%M %Y') AS MonthNameAndYear FROM DemoTable;
This will produce the following output −
+------------------+ | MonthNameAndYear | +------------------+ | April 2013 | | January 2014 | | September 2016 | | December 2018 | | April 2019 | +------------------+ 5 rows in set (0.02 sec)
Advertisements