如何将月-年转换为 MySql 中的月词?
How do I convert month-year to a month word in MySql?
我正在使用 MySql 5.5.37。我有 month-year numbesr 列,例如
201601
如何将其转换为后面跟着年份的月份?也就是说,上面会被转换成
January, 2016
?
第一次转换使用str_to_date()
,第二次转换使用date_format()
。格式字符为 %Y
表示 four-digit 年,%m
表示 two-digit 月,%M
表示月份字符串(例如 "January" )
select
str_to_date('201601', '%Y%m')
, date_format(str_to_date('201601', '%Y%m'), '%M, %Y')
输出将是
| 2016-01-00 | January, 2016 |
基本上首先通过在 table 中提供模式来使用 STR_TO_DATE() 函数并检索数据值,然后根据需要使用 DATE_FORMAT() 函数对其进行格式化。
SELECT DATE_FORMAT(STR_TO_DATE(field_name, '%Y%m'), '%M, %Y')
FROM table_name
您的字段是字符串还是数字都没有关系。
使用函数date_format.
示例
select date_format('2016-01-01', '%M, %Y');
-- returns January, 2016
并且需要将201601
转换为日期时间对象,使用函数str_to_date. Note that 201601
will need a day-of-month component, which we can add by concatenating 01
使其成为20160101
示例
select str_to_date('20160101', '%Y%m%d');
-- returns 2016-01-01
结合两者,
select date_format(str_to_date(concat('201601', '01'), '%Y%m%d'), '%M, %Y')
-- returns January, 2016
我正在使用 MySql 5.5.37。我有 month-year numbesr 列,例如
201601
如何将其转换为后面跟着年份的月份?也就是说,上面会被转换成
January, 2016
?
第一次转换使用str_to_date()
,第二次转换使用date_format()
。格式字符为 %Y
表示 four-digit 年,%m
表示 two-digit 月,%M
表示月份字符串(例如 "January" )
select
str_to_date('201601', '%Y%m')
, date_format(str_to_date('201601', '%Y%m'), '%M, %Y')
输出将是
| 2016-01-00 | January, 2016 |
基本上首先通过在 table 中提供模式来使用 STR_TO_DATE() 函数并检索数据值,然后根据需要使用 DATE_FORMAT() 函数对其进行格式化。
SELECT DATE_FORMAT(STR_TO_DATE(field_name, '%Y%m'), '%M, %Y')
FROM table_name
您的字段是字符串还是数字都没有关系。
使用函数date_format.
示例
select date_format('2016-01-01', '%M, %Y');
-- returns January, 2016
并且需要将201601
转换为日期时间对象,使用函数str_to_date. Note that 201601
will need a day-of-month component, which we can add by concatenating 01
使其成为20160101
示例
select str_to_date('20160101', '%Y%m%d');
-- returns 2016-01-01
结合两者,
select date_format(str_to_date(concat('201601', '01'), '%Y%m%d'), '%M, %Y')
-- returns January, 2016