How can Oracle convert a string to a date?
In Oracle, you can use the TO_DATE function to convert a string into a date.
Grammar:
TO_DATE(string, format_template)
For example, converting the string ‘2021-10-15’ to a date:
SELECT TO_DATE(‘2021-10-15’, ‘YYYY-MM-DD’) FROM dual;
‘YYYY-MM-DD’ is a format template that represents the year-month-day format.
If the string includes a time component, you can use the following format template:
- ‘YYYY-MM-DD HH24:MI:SS’ indicates the format of year-month-day hour:minute:second.
- ‘YYYY-MM-DD HH24:MI:SS.FF’ represents the format of year-month-day hour:minute:second.millisecond.
For example, convert the string ‘2021-10-15 08:30:00’ to a date:
SELECT TO_DATE(‘2021-10-15 08:30:00’, ‘YYYY-MM-DD HH24:MI:SS’) FROM dual;
Please note that the string and the format template must match, otherwise an exception will be thrown.