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)
Updated on: 2019-07-30T22:30:25+05:30

144 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements