How to convert this timestamp in PLSQL?

154 Views Asked by At

Using PL/SQL I have a TIMESTAMP(6) like this: 21-APR-22 02.25.00.000000 PM.

I need to convert it to format YYYY-MM-DD HH24:MI:SS (EX: 2022-04-21 14:25:00).

EDIT: I also need to store it as a VARCHAR

declare ts TIMESTAMP(6) :='21-APR-22 02.25.00.000000 PM'; 
dt VARCHAR(102); 
begin 
  dt:= TO_CHAR('19-APR-21 02.25.00.000000 PM','YYYY-MM-DD HH24:MI:SS'); 
  dbms_output.put_line(dt); 
  commit; 
END; 
[Error] Execution (50: 1): ORA-06502: PL/SQL: numeric or value error: character to number conversion error ORA-06512: at line 5
2

There are 2 best solutions below

0
On

Use

TO_CHAR(ts, 'YYYY-MM-DD HH24:MI:SS')

with ts holding the timestamp value you want to turn into a varchar value matching to the desired format.

See this example (on dbfiddle.uk).

1
On
declare ts TIMESTAMP(6) :='21-APR-22 02.25.00.000000 PM'; 
dt VARCHAR(102); 
begin 
  dt:= TO_CHAR(ts,'YYYY-MM-DD HH24:MI:SS'); 
  dbms_output.put_line(dt); 
  commit; 
END;