SELECT TO_CHAR((select logical_date -1 from logical_date
where logical_date_type='B'),'DD/MM/YYYY HH24:MI:SS') FROM DUAL;
This Query returns 23/04/2016 00:00:00
o/p of select logical_date -1 from logical_date where logical_date_type='B' :4/23/2016
SELECT TO_DATE((select logical_date -1 from logical_date
where logical_date_type='B'),'DD/MM/YYYY HH24:MI:SS') FROM DUAL;
This Query returns 4/23/0016
.
How do I get the format given by TO_CHAR using TO_DATE ??
Firstly, DATE doesn't have any format. Oracle does not store dates in the format you see. It stores it internally in 7 bytes with each byte storing different components of the datetime value.
The format is only for display purpose. TO_DATE is used to convert a literal into date, and has nothing to do with formatting. To display a date in your desired format, use TO_CHAR with proper FORMAT MODEL.
Also, remember, formatting has an order of precedence:
Let's see the chronological order of precedence, i.e. starting from highest to least:
Using TO_CHAR or TO_DATE at the individual SQL statement
ALTER SESSION SET NLS_DATE_FORMAT=’whatever format model you want’;
Setting it as an OS environment variable on the client machine
Setting of
NLS_DATE_FORMAT
is in the database initialization parametersFor example,
Individual SQL statement:
Session level:
This is wrong.
Never apply TO_DATE on a DATE column. It forces Oracle to:
based on the locale-specific NLS settings. You need TO_DATE to convert a literal into date. For date-arithmetic, leave the date as it is.
Dates do not have any intrinsic format. Oracle has an internal representation which doesn't look like anything you'd recognise as a date. The client or application decides how to display the date (e.g. using NLS_DATE_FORMAT), or you can use
TO_CHAR
to convert the date to a string with a format you specify, as you're doing in your first example.In your second example you are doing an implicit comversion of your actual date to a string, using your NLS setting - losing the century in the process, so presumably that has YY rather than YYYY - and then you convert that back to a date. I'm surprised that doesn't error as you are swapping the month and day positions.
Do not do that. Converting to a string and back to a date is pointless, even if your settings don't lose information on the way.
If you want it as a date for a client or other process to use just do:
If you want to compare against another date then still leave it as a date:
If you want to specify the format for display then use:
The problem is related to the default date format for your session that is configured in your oracle client settings To check the NLS_DATE_FORMAT settings for your Session
here's how you can change this setting for your session to achieve the desired results: