Oracle SQL无法将字符串日期转换为日期

时间:2013-04-21 12:20:00

标签: sql oracle date format

我需要转换以下日期,但我收到错误:

  

ORA-01841 :(完整)年份必须介于-4713和+9999之间,而不是0

和SQL:

SELECT TO_CHAR(TO_DATE('December 25th, 2004', 'MONTH DD, YYYY'), 'DD-MM-YY') FROM dual;

我认为因为字符串日格式而出现错误: 25th

如果我从字符串中删除'th'它正在工作但我需要转换它。

3 个答案:

答案 0 :(得分:3)

要照顾所有这些结局,请使用替换4次:

with q as (
        select 'December 25th, 2004' dt from dual
        union
        select 'August 1st, 2004'  dt from dual
        union
        select 'December 2nd, 2004' dt from dual
        union
        select 'December 3rd, 2004' dt from dual
       )
select to_char( to_date(replace(replace(replace(replace(dt, 
                                   'th,', ''), 
                                   'st,', ''), 
                                   'nd,',''),
                                   'rd,',''),
                                    'MONTH DD YYYY'), 'DD-MM-YY') from q

答案 1 :(得分:1)

如果用双引号括起来,可以在格式掩码中添加任意文字。

SQL> ed
Wrote file afiedt.buf

  1  SELECT TO_CHAR(TO_DATE('December 25th, 2004', 'MONTH DD"th", YYYY'),
  2                 'DD-MM-YY')
  3*   FROM dual
SQL> /

TO_CHAR(
--------
25-12-04

当然,这仅在字符串始终包含文字字符串th时才有效。如果您有其他字符串具有其他后缀(即December 1st, 2004),您将收到错误

SQL> ed
Wrote file afiedt.buf

  1  SELECT TO_CHAR(TO_DATE('December 1st, 2004', 'MONTH DD"th", YYYY'),
  2                 'DD-MM-YY')
  3*   FROM dual
SQL> /
SELECT TO_CHAR(TO_DATE('December 1st, 2004', 'MONTH DD"th", YYYY'),
                       *
ERROR at line 1:
ORA-01861: literal does not match format string

如果你想同时处理两者,你可能需要解析原始字符串以删除后缀,然后再将字符串转换为日期然后再转换回另一个字符串

SQL> ed
Wrote file afiedt.buf

  1  WITH x AS (
  2    SELECT 'December 1st, 2004' str FROM dual UNION ALL
  3    SELECT 'December 25th, 2004' FROM dual
  4  )
  5  SELECT TO_CHAR(
  6           TO_DATE( SUBSTR( str, 1, INSTR( str, ',' ) - 3 ) ||
  7                      SUBSTR( str, INSTR( str, ',' ) ),
  8                    'MONTH DD, YYYY' ),
  9           'DD-MM-YY' )
 10*   FROM x
SQL> /

TO_CHAR(
--------
01-12-04
25-12-04

答案 2 :(得分:1)

如果没有thst等等,它将起作用,即:

SELECT TO_CHAR(TO_DATE(
       REGEXP_REPLACE('December 25th, 2004',  
                      '([[:digit:]]{1,2})(st|nd|rd|th)', '\1'), 
                      'MONTH DD, YYYY'), 'DD-MM-YY')
  FROM dual;

因此,此表达式会删除与stndrdth连接的任何一个或两个数字组合,并从中计算日期。

希望这有帮助......干杯!