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;
First, you can use
SYSTIMESTAMPto return aTIMESTAMP 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 takeSYSDATEand convert it to a timestampYou can then convert
SYSTIMESTAMPto whatever time zone you want (‘CST6CDT’ in this case)And then if you want to specify the format of the string, you can add a
to_char