Question

I am having trouble converting a datetime field into date. Here is the query:

SELECT TO_DATE(PROJ.RECEIVEDDATE, 'MM/dd/yyyy')
FROM PROJ

But when I run it I get the following error, "ORA-01843: not a valid month"

So I tried to convert to char first then to date

SELECT TO_DATE(TO_CHAR(PROJ.RECEIVEDDATE, 'MM/dd/yyyy'), 'MM/dd/yyyy')
FROM PROJ

But get the wrong output, "2005-01-18 00:00:00.0"

Was it helpful?

Solution

I think you're a little confused about the DATE data type, as that has a time component - there isn't a separate DATETIME type in Oracle. If your RECEIVEDDATE field is already a DATE, as seems to be the case, then you're converting it unnecessarily, but you're also doing an implicit conversion to a string in the middle.

TO_DATE(PROJ.RECEIVEDDATE, 'MM/dd/yyyy')

is really doing

TO_DATE(TO_CHAR(PROJ.RECEIVEDDATE, <NLS_DATE_FORMAT>), 'MM/dd/yyyy')

... and the ORA-08143 error suggests you NLS format might be DD/MM/YYYY. When the day part of the date is greater than 12, you can expect that kind of error, since there is no month with a number greater than 12. It looks like you're working with 2005-01-18, so it's trying to interpret 18 as a month, so the error is reasonable.

From how you've phrased the first part of the question I think you're trying to strip the time portion of the field, which your second query is doing - that works since you have an explicit date format model this time. But doing two conversions isn't really necessary, you can use the TRUNC function to do that:

SELECT TRUNC(PROJ.RECEIVEDDATE)
FROM PROJ

The final part is a bit confusing though - that isn't 'wrong', it's how you're client is choosing to format the DATE value. If you want to see it in a particular format, just use TO_CHAR, and then you don't even need the TRUNC:

SELECT TO_CHAR(PROJ.RECEIVEDDATE, 'mm/dd/yyyy')
FROM PROJ

... but it depends what you're doing - if you're using it purely for display that's fine, if it will be used elsewhere in a bigger query then leave it as a DATE.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top