Oracle Time Zones Conversion (using from_tz)

2019-04-28 17:01发布

I'm trying to convert a time (date + time) from one time zone to another. In the query below, I'm trying to convert a time from EST ("America/New_York") to PST ("America/Los_Angeles"). The query is partially working; the results:

DATABASE_DATE = 2012-02-13 1:00:00 PM  
LOCALTIME (what I get): 2012-02-12 10:00:00 AM.

So the time is good but the date is wrong. It should be 2012-02-13 instead of 2012-02-12.

Am I doing something wrong? Here's my query:

select to_date( to_char( ( from_tz( to_timestamp( DATABASE_DATE
                                                 , 'YYYY-MM-DD HH:MI:SS')
                                   ,'America/New_York')
                          at time zone 'America/Los_Angeles')
                       ,'YYYY-MM-DD HH:MI:SS')
               ,'YYYY-MM-DD HH:MI:SS') as localtime
 from table

Thanks

3条回答
看我几分像从前
2楼-- · 2019-04-28 17:40

to_timestamp() gets a string (VARCHAR2, CHAR ...) if you try to give it a date, then oracle will convert it to a string according to NLS_DATE_FORMAT which might vary in different environments and return unexpected results (as in this case).
What you should do is use to_char first, so your query can look like this:

select to_date(to_char((from_tz(to_timestamp(to_char(DATABASE_DATE, 'YYYY-MM-DD HH:MI:SS PM'), 'YYYY-MM-DD HH:MI:SS PM') ,'America/New_York')
at time zone 'America/Los_Angeles'),'YYYY-MM-DD HH:MI:SS PM'),'YYYY-MM-DD HH:MI:SS PM') as localtime
from table

UPDATE: if I understand you right then you want something like this:

select to_char((from_tz(to_timestamp(to_char(DATABASE_DATE, 'YYYY-MM-DD HH:MI:SS PM'), 'YYYY-MM-DD HH:MI:SS PM') ,'America/New_York')
    at time zone 'America/Los_Angeles'),'YYYY-MM-DD HH:MI:SS PM TZD') as localtime
    from table
查看更多
戒情不戒烟
3楼-- · 2019-04-28 17:52
SELECT TO_CHAR(NEW_TIME(systimestamp,'EST','PST'), 'DD-MON-YY HH24:MI:SS') AS converted_timestamp_column FROM DUAL;
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-04-28 17:53

Please try this as well .There is a function for this purpose in oracle

https://docs.oracle.com/cd/B28359_01/olap.111/b28126/dml_functions_2036.htm

select NEW_TIME (TO_DATE ('2011/11/11 01:45', 'yyyy/mm/dd HH24:MI'), 'AST', 'MST') from dual;
查看更多
登录 后发表回答