MYSQL: How to convert a string into a month (Number) [duplicate]

我只是一个虾纸丫 提交于 2019-12-06 08:53:44

问题


I have the short version of months: JAN, FEB, MAR, etc.

and would like to convert them to it's respective numeric value: 1, 2, 3, etc

Also, I would like to be able to change back and forth between the numeric-month-value, to a "short" month name (JAN, FEB, MAR) and it's long version (January, February, March, etc)



NOTE: As @dipu-raj pointed out, this is not a duplicate because I am asking the opposite to MySQL MONTHNAME() from numbers and the answer IS different as well BECAUSE it requires different functions


回答1:


To convert abbrevation to full month name use:

mysql> select monthname(str_to_date('Mar','%b'));
+------------------------------------+
| monthname(str_to_date('Mar','%b')) |
+------------------------------------+
| March                              |
+------------------------------------+

To convert abbrevation to number use:

mysql> select month(str_to_date('Mar','%b'));
+--------------------------------+
| month(str_to_date('Mar','%b')) |
+--------------------------------+
|                              3 |
+--------------------------------+



回答2:


You probably need to familiarize yourself with the MySQL Date functions. For your case STR_TO_DATE() and DATE_FORMAT() would seem to be most useful. here is a link to the information:

https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date




回答3:


JAN to its month number; substitute your column/value where you see FEB below:

date_format(str_to_date(concat(2012, 'FEB'), '%Y%b'), '%m')
                                     ^^^^^

1 to its short month name; substitute your column/value where indicated:

 date_format(str_to_date(concat('2012-', 1), '%Y-%m'), '%b')
                                         ^

Use %M instead of %b as the last value above to get the long month name.




回答4:


Try this one:

    $date = 'Jan';
    echo 'Month number is '.date('n', strtotime($date)).'</br>';
    echo 'and its '.date('F', strtotime($date));

Use PHP Manual - Date/Time Functions for more format options.



来源:https://stackoverflow.com/questions/15708335/mysql-how-to-convert-a-string-into-a-month-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!