简体   繁体   中英

I want to convert this date format 1970-01-01T00:00:00-08:00 to only dd/mm/yyyy in oracle. But by using below query i'm getting error in conversion

I'm using this Query

SELECT CAST(TO_TIMESTAMP_TZ(REPLACE('1970-01-01T00:00:00-08:00', 'T', ''), 
                                    'YYYY-MM-DD HH:MI:SS TZH:TZM') AS DATE) DOB FROM dual;

Output is

ORA-01849: hour must be between 1 and 12 01849. 00000 - "hour must be between 1 and 12"

I need the output only as MM/DD/YYYY

Time format is 24 hours, so the fix is to use HH24 instead of HH .

SELECT CAST(TO_TIMESTAMP_TZ(
    REPLACE('1970-01-01T00:00:00-08:00', 'T', ''),
    'YYYY-MM-DD HH24:MI:SS TZH:TZM') AS DATE) DOB 
FROM dual;

But instead of using replace, you can use literal "T" in the pattern:

SELECT CAST(
    TO_TIMESTAMP_TZ('1970-01-01T00:00:00-08:00', 
        'YYYY-MM-DD"T"HH24:MI:SS TZH:TZM') 
    AS DATE) DOB FROM dual;

Be advised that the cast just drops the timezone info. If you need to convert the timestamps to date at a particular timezone (say +04:00), use at time zone clause on TIMESTAMP WITH TIME ZONE :

SELECT CAST(
    TO_TIMESTAMP_TZ('1970-01-01T00:00:00-08:00', 
        'YYYY-MM-DD"T"HH24:MI:SS TZH:TZM') 
    at time zone '+04:00' AS DATE) DOB FROM dual;

See more at:


Since you want output in format MM/DD/YYYY , use to_char on the timestamp directly:

SELECT to_char(
    TO_TIMESTAMP_TZ('1970-01-01T00:00:00-08:00', 
        'YYYY-MM-DD"T"HH24:MI:SS TZH:TZM') 
    at time zone '+04:00', 'MM/DD/YYYY') DOB FROM dual;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM