Home > Blockchain >  MYSQL - Get Month Number from Month Name
MYSQL - Get Month Number from Month Name

Time:11-20

 ------------ 
| MonthNum   |
 ------------ 
| 1          |
| 2          |
| 3          |
| 4          |
| 5          |
| 6          |
| 7          |
| 8          |
| 9          |
| 10         |
| 11         |
| 12         |
 ------------ 

Query to convert Month Number to Month Name

mysql> select monthname(str_to_date(MonthNum,'%m')) as MonthName from MonthDemo;

The following is the output.

 ----------- 
| MonthName |
 ----------- 
| January   |
| February  |
| March     |
| April     |
| May       |
| June      |
| July      |
| August    |
| September |
| October   |
| November  |
| December  |
 ----------- 

How can we do it the other way around? From Month Name to Month Number? I tried this and it isn't working

select monthname(str_to_date(MonthName,'%c')) as MonthName;

Tried the solution in this link but still not working.

CodePudding user response:

If you build a valid date with day, month, and year components, and then use the MONTH() function on the resulting date, it should work.

SELECT MONTH(STR_TO_DATE(CONCAT(MonthName, '-01-2022'), '%M-%d-%Y')) AS MonthName;  -- 1

Demo

  • Related