简体   繁体   中英

Oracle SQL Query TO_DATE

I have a question regarding the following query in Oracle SQL:

SELECT TO_DATE('10-11-2015','DD-MM-YYYY') FROM DUAL;

When I run it the result is the following 10-NOV-15 . From what I read in the Oracle docs the YYYY should convert to a 4-digit year but it converts into 2-digit year. Why is this happening?

The date is being set with a 4-digit year.

However, you are being shown the date using the default format that Oracle is currently using to display dates in your user's session. The default format Oracle uses for implicit date conversions depends on the territory. For America (among others) this is DD-MON-RR and will have a 2-digit year; but for Sweden the default is RRRR-MM-DD and a 4-digit year will be displayed.

This format can be set using:

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-RR';

So, if instead you set the default format to YYYY-MM-DD (the ISO-8601 date format) using:

ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD';

Then your query:

SELECT TO_DATE('10-11-2015','DD-MM-YYYY') FROM DUAL;

Would output 2015-11-10 .

If you want a specific format for a date then you should not rely on implicit conversions as ANY user can set their own format at ANY time and you will not get consistent outputs; instead you should use an explicit conversion:

SELECT TO_CHAR( TO_DATE('10-11-2015','DD-MM-YYYY'), 'DD-MM-YYYY' ) FROM DUAL;

Would output 10-11-2015 .

You can see that this isn't happening by using extract() :

SELECT EXTRACT( YEAR FROM TO_DATE('10-11-2015','DD-MM-YYYY') ) FROM DUAL; 

The two digit year is only how the value is being presented.

Alternative of using below can be better:

SELECT TO_DATE('10-11-2015','DD-MM-RRRR') FROM DUAL;

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