Domanda

I have the following queries:

SELECT to_date(to_char(to_date('01-FEB-1949'))) FROM DUAL;  
/*this returns 2/1/2049. */

SELECT to_date(to_char(to_date('01-FEB-1949'),'dd-MON-yyyy')) FROM DUAL; 
/*this returns 2/1/1949.*/

Why does the first one returns the year 2049 instead of 1949?

By Googling I have found that I can "force" the client date format to be the one desire by changing the keyon the registry:

KEY_OraClient11g_home1
NLS_DATE_FORMAT : YYYY/MM/DD
È stato utile?

Soluzione

You're doing multiple implicit date conversions in both versions. This:

SELECT to_date(to_char(to_date('01-FEB-1949'))) FROM DUAL; 

is equivalent to:

SELECT to_date(to_char(to_date('01-FEB-1949', <NLS_DATE_FORMAT>),
    <NLS_DATE_FORMAT>, <NLS_DATE_FORMAT>)) FROM DUAL;

whereas the second query has one of those replaced with a specific format. It looks like your default format - which you can set, I believe, in the Toad preferences without modifying the registry directly; it isn't clear if you're even modifying something related to Toad - is DD-MON-RR, as shown by plugging that into these queries:

SELECT to_date(to_char(to_date('01-FEB-1949','DD-MON-RR'),
        'DD-MON-RR'),'DD-MON-RR') AS date1,
    to_date(to_char(to_date('01-FEB-1949','DD-MON-RR'),
        'dd-MON-yyyy'),'DD-MON-RR') AS date2 FROM DUAL;

DATE1                            DATE2
February, 01 2049 00:00:00+0000  February, 01 1949 00:00:00+0000

(SQL Fiddle)

You can see in this SQL Fiddle that in the first version, the date appears as a string with the year as 49 rather than 1949, and that is then interpreted - by the RR mask - as 2049, which is the expected behaviour.

Short version: never rely on implicit date conversions or the NLS date format mask.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top