【问题标题】:MYSQL: How to convert a string into a month (Number) [duplicate]MYSQL:如何将字符串转换为月份(数字)[重复]
【发布时间】:2018-11-03 02:38:59
【问题描述】:

我有月份的短版:JAN, FEB, MAR

并希望将它们转换为相应的数值:1, 2, 3

另外,我希望能够在数字月份值之间来回更改,以“短”月份名称(JAN, FEB, MAR)和长版本(January, February, March 等)



注意:正如@dipu-raj 指出的那样,这不是重复的,因为我问的是与MySQL MONTHNAME() from numbers 相反的问题答案不同好吧,因为它需要不同的功能

【问题讨论】:

标签: mysql string-conversion date-conversion


【解决方案1】:

要将缩写转换为完整的月份名称,请使用:

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

将缩写转换为数字使用:

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

【讨论】:

  • +1 - 很好:我的解决方案让天为零,但我不认为年份也可能为零;这干净多了。
  • 另一种方式:SELECT FIELD(month, 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') 其中month 是 1-12 将根据数字为您提供月份名称。
【解决方案2】:

您可能需要熟悉 MySQL 日期函数。对于您的情况,STR_TO_DATE()DATE_FORMAT() 似乎是最有用的。这是信息的链接:

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

【讨论】:

    【解决方案3】:

    JAN 到它的月份数;替换您在下面看到FEB 的列/值:

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

    1 到它的短月份名称;在指示的地方替换您的列/值:

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

    使用%M 而不是%b 作为上面的最后一个值来获取长月份名称。

    【讨论】:

      【解决方案4】:

      试试这个:

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

      使用PHP Manual - Date/Time Functions 获取更多格式选项。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        • 1970-01-01
        • 2011-06-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多