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
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 |
+--------------------------------+
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
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.
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