0

Have done a lot of search before asking this question, like How to convert a string into date format, How to convert a string into date, but still can't figure it out.

So, here's the question, how to convert these string dates into date in Oracle:

"2016-08-15 10:45:30" (String type) -> 20160815 (Date type)

"20160815104530" (String type) -> 20160815 (Date type)

Any idea will be appreciated.

3
  • Do you want to preserve the time portions? Because, Oracle's DATE type does support date + time. Commented Aug 15, 2016 at 3:04
  • I should also mention that the posts you linked to are not for Oracle. You can't expect to find Oracle-useful info in posts for SQL Server or Excel. And why not go to the source anyways? Official TO_DATE documentation Commented Aug 15, 2016 at 3:12
  • I just want to get date, no time portions need Commented Aug 15, 2016 at 3:12

2 Answers 2

1

You are mixing two things here:

The first is the conversion of a String data type, in Oracle VARCHAR2 into a DATE data type. The DATE data type has a precision of seconds, you can't change that. A DATE data type will always give you the date and time component, i.e year, month, day, hours, minutes and seconds: Oracle SQL Data Type Documentation

However, the second part of what you are asking is about how to format the date when retrieved. This is helpful when running reports, or other kinds of visual display of dates. For example, in the US you would most likely want your date columns appear in the format MM/DD/YYYY while everywhere else in the world you most likely want to stick with DD/MM/YYYY. Oracle lets you do that by telling it what NLS_DATE_FORMAT you want to use. You can set that parameter for each individual session as well as on database level, it is up to you (and your DBA) to decide where and when you want to set that. In your case you can apply this via the ALTER SESSION command:

SQL> ALTER SESSION SET nls_date_format='YYYY-MM-DD';

Session altered.

SQL> SELECT TO_DATE('2016-08-15 10:45:30', 'YYYY-MM-DD HH24:MI:SS') FROM DUAL;

TO_DATE(
----------
2016-08-15

SQL> SELECT TO_DATE('20160815104530', 'YYYYMMDDHH24MISS') FROM DUAL;

TO_DATE(
----------
2016-08-15
Sign up to request clarification or add additional context in comments.

Comments

1

You use to_date():

select to_date(substr(str1, 1, 10), 'YYYY-MM-DD')
select to_date(substr(str2, 1, 8), 'YYYYMMDD')

2 Comments

Thank you, but it shows up: 2016-08-15 00:00:00 when execute select to_date(substr(str2, 1, 8), 'YYYYMMDD'), how can I just get the date according to the format of YYYYMMDD?
@triffic . . Use to_char(). In Oracle, the date type includes the time as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.