17

我有类似下面的东西-

EXTRACT(HOUR from CAST(to_char(tran_datetime,'DD-MON-YYYY HH24:MI:SS') AS TIMESTAMP))

tran_datetimeDATE类型。这会给某些行说错误HOUR must be between 1 and 12,所以我知道它不能以24 Hour格式(或军事时间)处理 Hour。以下作品(显然) -

EXTRACT(HOUR from CAST(to_char(tran_datetime,'DD-MON-YYYY HH:MI:SS') AS TIMESTAMP)) 

或者

EXTRACT(HOUR from CAST(tran_datetime AS TIMESTAMP))  --12 Hr format by default

有没有办法使用EXTRACT()24HOUR小时格式,即 15 表示下午 3 点,13 表示下午 1 点等。

请注意 -to_char(tran_datetime,'HH24')是一个非常明显的选项,但我希望EXTRACT()专门使用功能。

4

3 回答 3

24

问题不在于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
于 2012-10-16T15:04:00.597 回答
14
select to_char(tran_datetime,'HH24') from test;

TO_CHAR(tran_datetime,'HH24')
------------------
16      
于 2012-10-16T14:42:23.907 回答
1

简单易行的解决方案:

select extract(hour from systimestamp) from dual;

EXTRACT(HOURFROMSYSTIMESTAMP)
-----------------------------
                           16 
于 2021-02-05T16:30:21.330 回答