简体   繁体   中英

Convert timestamp/date time from UTC to EST Oracle SQL

I have a field with a date/time value like this:

2009-11-17 18:40:05

It's in UTC. In the query how can I convert this to EST?

I'm trying something like this but it throws an error.

// datetime is the field name
SELECT 
   FROM_TZ(TIMESTAMP TO_DATE(datetime, 'yyyy-mm-dd hh24miss'), 'EST') AS DT
FROM
   db_name

I had to tweak it slightly to get it to work on my database, but this worked:

select from_tz(to_timestamp('2009-11-17 18:40:05','yyyy-mm-dd hh24:mi:ss'), 'UTC') 
at time zone 'America/New_York' from dual

The key is the "at time zone" syntax.

If you want to convert a date field from UTC to EST, this worked for me:

CAST(FROM_TZ(CAST(DATE_FIELD AS TIMESTAMP), 'UTC') 
at time zone 'America/New_York' AS Date) as DESIRED_FIELD_NAME

First, I cast the desired date field (as DATE_FIELD) to a timestamp. The result of the cast is the first parameter of the FROM_TZ function, which requires the parameter to be of type TIMESTAMP. The second parameter is 'UTC', since that is what we are changing from.

Then, I cast the results of that function call back to type DATE and give it an alias.

select to_char(systimestamp at time zone 'EST','HH') EST_TIME,
    TO_CHAR(SYSDATE,'HH') EDT_TIME,
    NEW_TIME(SYSDATE,
        (
            CASE 
                WHEN to_char(systimestamp at time zone 'EST','HH') = TO_CHAR(SYSDATE,'HH') 
                THEN 'EST'
                ELSE 'EDT'
            END
        ),'GMT') 
    from dual

Try this in ORACLE, I am using 12.2.0.1.0 64bit

SELECT * FROM v$version; --find version information
SELECT SYSDATE UTC, NEW_TIME(SYSDATE, 'GMT', 'EST') EST FROM DUAL; --will give both zones

This worked for me, should work for you too.

An alternate approach to get the date and time can be,

from_tz(CAST(DATE_FIELD AS TIMESTAMP), 'UTC') at time zone 'America/New_York' as DESIRED_FIELD_NAME

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