Walter Moore
Walter Moore

Reputation: 77

How do I convert timezone in oracle sql stored procedure?

How do I convert a date/timeztamp from one timezone to another timezone in an Oracle SQL stored procedure? The DB server is set to use GMT, as is the machine which connects to the DB, but the data must be saved in CST or CDT, depending on whether it is daylight savings time or not.

I have this SQL working:

select to_char(from_tz(TO_TIMESTAMP(to_char(SYSDATE,'mm-dd-yyyy hh24:mi:ss'), 'mm-dd-yyyy hh24:mi:ss'),'GMT')  at time zone 'CST6CDT','mm-dd-yyyy hh24:mi:ss') from dual;

But when I put it into a procedure, it fails with this error: ORA-01843: not a valid month

This is what I have for the procedure:

declare 
p_systemDT TIMESTAMP WITH TIME ZONE;
BEGIN
select to_char(from_tz(TO_TIMESTAMP(to_char(SYSDATE,'mm-dd-yyyy hh24:mi:ss'), 'mm-dd-yyyy hh24:mi:ss'),'GMT')  at time zone 'CST6CDT','mm-dd-yyyy hh24:mi:ss')  into p_systemDT  from dual;
DBMS_OUTPUT.PUT_LINE('p_systemDT = ' || p_systemDT);
end;

Upvotes: 3

Views: 4526

Answers (1)

Justin Cave
Justin Cave

Reputation: 231661

First, you can use SYSTIMESTAMP to return a TIMESTAMP WITH TIME ZONE (in my case, the server is running in the US/Eastern time zone which is 5 hours behind GMT) so you don't have to take SYSDATE and convert it to a timestamp

SQL> select systimestamp
  2    from dual;

SYSTIMESTAMP
---------------------------------------------------------------------------
10-DEC-12 12.39.51.755000 PM -05:00

You can then convert SYSTIMESTAMP to whatever time zone you want ('CST6CDT' in this case)

SQL> ed
Wrote file afiedt.buf

  1  select systimestamp at time zone 'CST6CDT'
  2*   from dual
SQL> /

SYSTIMESTAMPATTIMEZONE'CST6CDT'
---------------------------------------------------------------------------
10-DEC-12 11.40.14.491000 AM CST6CDT

And then if you want to specify the format of the string, you can add a to_char

SQL> ed
Wrote file afiedt.buf

  1  select to_char( systimestamp at time zone 'CST6CDT', 'mm-dd-yyyy hh24:mi:ss' )
  2*   from dual
SQL> /

TO_CHAR(SYSTIMESTAM
-------------------
12-10-2012 11:40:48

Upvotes: 1

Related Questions