Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle Time Zones Conversion (using from_tz)

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

like image 367
Mark Marina Avatar asked Feb 13 '12 16:02

Mark Marina


People also ask

How do I change timezone in Oracle?

Use the ALTER DATABASE SET TIME_ZONE command to change the time zone of a database. This command takes either a named region such as America/Los_Angeles or an absolute offset from UTC. This example sets the time zone to UTC: ALTER DATABASE SET TIME_ZONE = '+00:00';

What is From_tz?

FROM_TZ converts a timestamp value and a time zone to a TIMESTAMP WITH TIME ZONE value. time_zone_value is a character string in the format 'TZH:TZM' or a character expression that returns a string in TZR with optional TZD format. Examples.

Does Sysdate include timezone?

SYSDATE does not contain timezone information.

Does Oracle store timestamp in UTC?

Oracle does note store the data in specified format. You can use SYS_EXTRACT_UTC to get TIMESTAMP in UTC Timezone.


1 Answers

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
like image 55
A.B.Cade Avatar answered Oct 01 '22 18:10

A.B.Cade