简体   繁体   中英

SQL: Convert varchar to date

I have the following varchar type variable that I need to convert to date:

2019-07-24T13:52:04

When I do the following select:

SELECT TO_CHAR(TO_DATE(createddt,'YYYY-MM-DD T HH:MM:SS'), 'YYYY-MM-DD T HH:MM:SS')
FROM tbl$orders;

it gives me an error message:

date format not recognized.

How to convert this varchar to date?

I am going to speculate that you are using Oracle because it has to_date() and in Oracle, the date data type has a time component.

This then works:

select to_date('2019-07-24T13:52:04', 'YYYY-MM-DD"T"HH24:MI:SS')
from dual;

Is that what are you looking for

SELECT TO_DATE(REPLACE('2019-07-24T13:52:04', 'T', ' '), 'YYYY-MM-DD HH24:MI:SS')
FROM Dual;

Actually, Date format in Oracle is defined by NLS_DATE_FORMAT and you need to set it according to your requirement.

You are not able to see the letter T as your NLS_DATE_FORMAT is not set like that way.

You can try the following example for your problem:

ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD"T"HH24:MI:SS'; -- setting the date format to be displayed at the session level

SELECT
    TO_DATE('2019-07-24T13:52:04', 'YYYY-MM-DD"T"HH24:MI:SS')
FROM
    DUAL; -- Your query

Also, Please read about NLS_DATE_FORMAT from oracle documentation. It is really needed to understand how dates are stored and how it is displayed in oracle.

Cheers!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM