简体   繁体   中英

Oracle convert varchar to timeStamp gives ORA-01843: not a valid month

SYSCREATEDATE is saved as varchar2 in DB. Value is as follows:

SYSCREATEDATE
10/17/2006 7:44
11/29/2011 6:17
11/16/2011 11:46
2/27/2012 4:01
2/27/2012 4:01
2/27/2012 4:01

Now i want to convert the field to timestamp and pick dates less than a certain date say '06/01/2020'.

Tried this:

select * from legacy_case where  TO_TIMESTAMP(SYSCREATEDATE, 'MM/DD/YYYY HH:MI:SS') < '06/01/2020 00:00:00';

I am getting the below error:

ORA-01843: not a valid month
01843. 00000 -  "not a valid month"
*Cause:    
*Action:

Any input please?

Convert a sting literal to timestamp explicitly

select * 
from legacy_case 
where  TO_TIMESTAMP(SYSCREATEDATE, 'MM/DD/YYYY HH:MI:SS') < TO_TIMESTAMP('06/01/2020 00:00:00', 'MM/DD/YYYY HH24:MI:SS')

Several issues/comments:

  1. never store dates in varchar2 fields. use a proper DATE or TIMESTAMP data type to avoid parsing errors to begin with. This is just asking for trouble. Better to enforce validation with the proper data types.

  2. Is the date format in this field 12 hour AM/PM or 24 hours? I don't see any values > 11:xx so can't tell, but HH format is only for hours 1-12. If the timestamp string is 24 hour format, then you need to use HH24.

  3. Never use string literals in a comparison, always convert using to_date or to_timestamp, as the literal may not match the current NLS_DATE_FORMAT default and may not be parsed properly. You can see the default format with the following query:

select * from nls_session_parameters where parameter = 'NLS_DATE_FORMAT';

I tried to rewrite the statement to test your time format. It did throw ORA-01843.

SQL> select 'TRUE' "Compare" from dual where to_timestamp('10/17/2006 7:44', 'MM/DD/YYYY HH:MI:SS') < '06/01/2020 00:00:00';
select 'TRUE' "Compare" from dual where to_timestamp('10/17/2006 7:44', 'MM/DD/YYYY HH:MI:SS') < '06/01/2020 00:00:00'
                                                                                                 *
ERROR at line 1:
ORA-01843: not a valid month

The pointer (*) in the error message indicates that the string '06/01/2020 00:00:00' is the source of problem.

To make the comparison succeed, you should compare both sides on the same base. For example.

SQL> select 'TRUE' "Compare" from dual where to_timestamp('10/17/2006 7:44', 'MM/DD/YYYY HH24:MI:SS') < to_timestamp('06/01/2020 00:00:00','MM/DD/YYYY HH24:MI:SS');

Comp
----
TRUE

In the above query, I use TO_TIMESTAMP() function on both side, additionally, I use HH24 instead of your HH. This time, the test is passed.

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