问题不在于extract
,它当然可以处理“军事时间”。看起来你有一个默认的时间戳格式,HH
而不是HH24
; 或者至少这是我能看到重新创建它的唯一方法:
SQL> select value from nls_session_parameters
2 where parameter = 'NLS_TIMESTAMP_FORMAT';
VALUE
--------------------------------------------------------------------------------
DD-MON-RR HH24.MI.SSXFF
SQL> select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS')
2 as timestamp)) from dual;
EXTRACT(HOURFROMCAST(TO_CHAR(SYSDATE,'DD-MON-YYYYHH24:MI:SS')ASTIMESTAMP))
--------------------------------------------------------------------------
15
alter session set nls_timestamp_format = 'DD-MON-YYYY HH:MI:SS';
Session altered.
SQL> select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS')
2 as timestamp)) from dual;
select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS') as timestamp)) from dual
*
ERROR at line 1:
ORA-01849: hour must be between 1 and 12
因此,简单的“修复”是将格式设置为可以识别 24 小时的格式:
SQL> alter session set nls_timestamp_format = 'DD-MON-YYYY HH24:MI:SS';
Session altered.
SQL> select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS')
2 as timestamp)) from dual;
EXTRACT(HOURFROMCAST(TO_CHAR(SYSDATE,'DD-MON-YYYYHH24:MI:SS')ASTIMESTAMP))
--------------------------------------------------------------------------
15
尽管您根本不需要to_char
:
SQL> select extract(hour from cast(sysdate as timestamp)) from dual;
EXTRACT(HOURFROMCAST(SYSDATEASTIMESTAMP))
-----------------------------------------
15