0

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?

GMB
  • 216,147
  • 25
  • 84
  • 135
Shury
  • 468
  • 3
  • 15
  • 49

3 Answers3

2

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.

MT0
  • 143,790
  • 11
  • 59
  • 117
1

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.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Alternative of using below can be better:

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

  • Better how? It will produce the same result. The `RR` and `RRRR` format masks were a band-aid to deal with Y2K issues, but they just moved the problem to the middle of the century, which in a few more years will be closer than the start of it. A [standard date literal](https://docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/Literals.html#GUID-8F4B3F82-8821-4071-84D6-FBBA21C05AC1) is the safest format. – William Robertson May 17 '20 at 12:19