问题
In my application I am setting the NLS_DATE_FORMAT of the session to format all dates returned by the program using the following command:
alter session set nls_date_format='DY DDTH MON YYYY';
This should return the date like this: 'Fri 23rd Aug 2013'
However, if I run the following query:
select SYSDATE from dual;
I get the date in the following format: 'FRI 23 AUG 2013'. Notice the lack of the 'rd' after '23'.
If I run the following query:
select to_char(sysdate, 'DY DDTH MON YYYY') from dual;
The date does come back in the desired format. So why does the 'TH' date format parameter not work when setting it through NLS_DATE_FORMAT? And are there any other date format parameters that do work when using TO_CHAR but not through NLS_DATE_FORMAT?
Thanks for your help
By the way, I am using Oracle 11.2 client and database.
UPDATE
I was running the alter session command from within SQL Developer. I tried this in SQL PLUS and it returned the date in the correct format. However, now I am having a problem with inserting formatted dates.
If I do the following (after setting the NLS_DATE_FORMAT as above) I get a 'ORA-01861 literal does not match format string' error:
INSERT INTO DATE_TABLE (MY_DATE_COL) VALUES ('Thu 18th Apr 2013');
I would expect that to work after setting the NLS_DATE_FORMAT?
If I change the insert statement to:
INSERT INTO DATE_TABLE (MY_DATE_COL) VALUES ('Thu 18 Apr 2013');
Then it does work! Why is this?
回答1:
If you do:
alter session set nls_date_format='DD DDTH MON YYYY';
You get an error, ORA-01810: format code appears twice.
If you use the same format model as your TO_CHAR then it works:
alter session set nls_date_format='DY DDTH MON YYYY';
Session altered.
select SYSDATE from dual;
SYSDATE
-----------------
FRI 23RD AUG 2013
This works in SQL Developer and SQL*Plus.
For your updated question about inserting, the datetime format documentation says:
Notes on date format element suffixes:
When you add one of these suffixes to a datetime format element, the return value is always in English.
Datetime suffixes are valid only to format output. You cannot use them to insert a date into the database.
So you cannot use a string with the suffix as part of your insert, either explicitly or via the NLS_DATE_FORMAT. You would have to remove it from the string or tailor the format model to treat is as a fixed value.
回答2:
you have a typo in the alter session statment. set DY instead of DD on the first place
alter session set nls_date_format='DY DDTH MON YYYY';
回答3:
You can insert string literal 'Thu 18th Apr 2013' into a column of DATE data type as follows(enclosing th in the format model with double quotes):
INSERT INTO DATE_TABLE (MY_DATE_COL)
VALUES (to_date('Thu 18th Apr 2013', 'Dy DD"th" Mon YYYY'));
来源:https://stackoverflow.com/questions/18398237/oracle-nls-date-format-not-working-properly