提取()24小时格式的小时

时间:2012-10-16 14:12:04

标签: oracle

我有类似下面的内容 -

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格式(或军事时间)处理小时。以下作品(显然) -

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()以24小时格式获取HOUR,即下午3点15点,下午1点13点等等。

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

3 个答案:

答案 0 :(得分:16)

问题不在于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

答案 1 :(得分:6)

select to_char(tran_datetime,'HH24') from test;

TO_CHAR(tran_datetime,'HH24')
------------------
16      

答案 2 :(得分:-1)

简单易用的解决方案:

select extract(hour from systimestamp) from dual;

EXTRACT(HOURFROMSYSTIMESTAMP)
-----------------------------
                           16