EXTRACT() Hour in 24 Hour format

后端 未结 2 1024

I have something like below-

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

tran_datetime

相关标签:
2条回答
  • 2020-12-16 16:01

    The problem is not with extract, which can certainly handle 'military time'. It looks like you have a default timestamp format which has HH instead of HH24; or at least that's the only way I can see to recreate this:

    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
    

    So the simple 'fix' is to set the format to something that does recognise 24-hours:

    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
    

    Although you don't need the to_char at all:

    SQL> select extract(hour from cast(sysdate as timestamp)) from dual;
    
    EXTRACT(HOURFROMCAST(SYSDATEASTIMESTAMP))
    -----------------------------------------
                                           15
    
    0 讨论(0)
  • 2020-12-16 16:14
    select to_char(tran_datetime,'HH24') from test;
    
    TO_CHAR(tran_datetime,'HH24')
    ------------------
    16      
    
    0 讨论(0)
提交回复
热议问题