如何将日期转换成月数?(how to convert date into month number?

2019-07-17 14:29发布

我有一列本月我的表。 月份名称和日期都存储在本月列像

Month    
01-JAN-12 
02-FEB-12 

等等。

如何转换 日起一个月数如

Month
1 
2 

等等

Answer 1:

select 
to_char(to_date('01-JAN-12','dd-mon-yy'),'mm') from dual;


Answer 2:

提取完全适用于本

EXTRACT提取并返回指定日期时间字段的值

with fullYear as(
  select (to_date('01-jan-12') + 29*level) dte
    from dual
  connect by level <= 12
  )

select extract(month from dte) month, dte from fullYear ;

给你

MONTH       DTE
1           January, 30 2012 00:00:00+0000
2           February, 28 2012 00:00:00+0000
3           March, 28 2012 00:00:00+0000
4           April, 26 2012 00:00:00+0000
5           May, 25 2012 00:00:00+0000
6           June, 23 2012 00:00:00+0000
7           July, 22 2012 00:00:00+0000
8           August, 20 2012 00:00:00+0000
9           September, 18 2012 00:00:00+0000
10          October, 17 2012 00:00:00+0000
11          November, 15 2012 00:00:00+0000
12          December, 14 2012 00:00:00+0000


Answer 3:

使用TO_CHAR函数在TO_CHAR(my_column, 'MM')

为了您的具体格式,你需要的格式转换器TO_CHAR(month, 'FmMM')感谢尼古拉克拉斯诺夫对这一招)。

如果您的month列尚未日期类型的,你首先需要将其转换为一个日期: TO_CHAR(TO_DATE(month, 'DD-Mon-IY'), 'FmMM')



Answer 4:

完全同意关于书写时Oracle提供的内置功能的情况下:

SELECT EXTRACT(MONTH FROM DATE '2012-03-15') FROM DUAL;

SELECT EXTRACT(MONTH FROM TO_DATE('01-JAN-12', 'DD-MON-RR')) month_to_number FROM DUAL;

select to_number(to_char(to_date('01-JAN-12','dd-mon-yy'),'mm')) month_to_number from     dual;

select to_number(to_char(trunc(sysdate), 'mm')) month_to_number from dual;


Answer 5:

DATEPART函数做到这一点很容易

SELECT DATEPART(m, getdate()) 


Answer 6:

您可以使用“日期部分”功能太:

http://docs.oracle.com/cd/E10530_01/doc/epm.931/html_esb_techref/maxl/dml/funcs/datepart.htm



Answer 7:

        SELECT  ( CASE yourDate
        WHEN 'Jan' THEN 1
        WHEN 'Feb' THEN 2
        WHEN 'Mar' THEN 3
        WHEN 'Apr' THEN 4
        WHEN 'May' THEN 5
        WHEN 'Jun' THEN 6
        WHEN 'Jul' THEN 7
        WHEN 'Aug' THEN 8
        WHEN 'Sep' THEN 9
        WHEN 'Oct' THEN 10
        WHEN 'Nov' THEN 11
        WHEN 'Dec' THEN 12
       END )


文章来源: how to convert date into month number?