Rachanaa
Rachanaa

Reputation: 53

Not able to convert timestamp to char or date in oracle sql

I need to convert timestamp value(19-01-21 09:15:00.000000 PM) to date format('YYYY/MM/DD HH24:MI:SS') . I'm trying to do it using to_char function (to convert it to varchar and use it in TO_DATE function). I'm getting below error in to_char function. Is this the feasible way or please suggest if anything better works

select TO_CHAR('19-01-21 09:15:00.000000 PM','DD-MM-YY HH:MI:SSxFF AM') from dual; 
select TO_DATE(TO_CHAR('19-01-21 09:15:00.000000 PM','DD-MM-YYYY HH:MI:SSxFF AM'),'YYYY/MM/DD HH24:MI:SS'  ) from dual;

I'm getting below error:

ORA-01722: invalid number
01722. 00000 -  "invalid number"
*Cause:    The specified number was invalid.
*Action:   Specify a valid number.

Upvotes: 3

Views: 11778

Answers (1)

MT0
MT0

Reputation: 168505

'19-01-21 09:15:00.000000 PM' is a string literal; it is not a DATE or TIMESTAMP data type.

Since your string has fractional seconds, you can use TO_TIMESTAMP to convert it to a TIMESTAMP data type:

SELECT TO_TIMESTAMP( '19-01-21 09:15:00.000000 PM', 'DD-MM-RR HH12:MI:SS.FF6 AM' )
         AS timestamp_value
FROM   DUAL;

Which outputs:

| TIMESTAMP_VALUE               |
| :---------------------------- |
| 2021-01-19 21:15:00.000000000 |

If you want the value as a DATE data type then you can take the previous output and CAST it to a DATE:

SELECT CAST(
         TO_TIMESTAMP( '19-01-21 09:15:00.000000 PM', 'DD-MM-RR HH12:MI:SS.FF6 AM' )
         AS DATE
       ) AS date_value
FROM   DUAL;

or, if the fractional seconds are always going to be zero:

SELECT TO_DATE( '19-01-21 09:15:00.000000 PM', 'DD-MM-RR HH12:MI:SS".000000" AM' )
         AS date_value
FROM   DUAL;

Which both output:

| DATE_VALUE          |
| :------------------ |
| 2021-01-19 21:15:00 |

db<>fiddle here


I need to convert timestamp value to date/varchar value.

If you want to format the value as YYYY/MM/DD HH24:MI:SS then you can use TO_TIMESTAMP and then TO_CHAR:

SELECT TO_CHAR(
         TO_TIMESTAMP( '19-01-21 09:15:00.000000 PM', 'DD-MM-RR HH12:MI:SS.FF6 AM' ),
         'YYYY/MM/DD HH24:MI:SS'
       ) AS date_string
FROM   DUAL;

Which outputs:

| DATE_STRING         |
| :------------------ |
| 2021/01/19 21:15:00 |

(Note: this outputs a string data type and not a DATE data type; if you want a DATE data type then use the 2nd or 3rd example.)

db<>fiddle here

Upvotes: 4

Related Questions