想要将多日期格式转换为此格式" yyyy-mm-dd"在oracle

时间:2014-12-03 12:19:24

标签: oracle date

用户提供任何日期格式值

Select To_Date('20-11-2014','yyyy-mm-dd')  From Dual ;

(或)

Select To_Date('2014-11-28','yyyy-mm-dd')  From Dual ;

但我们希望转换为单一格式(此格式)

select to_char(to_date(trunc(datereceipt), 'DD-MM-YYYY'), 'yyyy-mm-dd') from vttrcwfheggrecivdlot

datereceipt := '20-11-2014';

(此格式适用于上述查询)

但是

datereceipt := '2014-11-28';

(对于使用此格式,想要在datediff函数中转换日期格式,所有操作都在运行时执行)

2 个答案:

答案 0 :(得分:1)

如果只有这两种日期格式,则可以:

select decode(instr(:datereceipt, '-'), 3,   to_char(to_date(:datereceipt, 'DD-MM-YYYY'), 'yyyy-mm-dd'), :datereceipt) 
from dual

或者如果你想要它们作为日期

select decode(instr(:datereceipt, '-'), 3,  to_date(:datereceipt, 'DD-MM-YYYY'), to_date(:datereceipt, 'yyyy-mm-dd')) 
from dual

答案 1 :(得分:0)

您可能需要接受不同格式的日期输入(字符串),但您只需要将它们转换为日期,而不是格式化的字符串。可以使用这样的函数:

function my_to_date (p_str varchar2) return date
is
begin
   return to_date (p_str, 'DD/MM/YYYY');
exception
   when others then
      return to_date (p_str, 'YYYY-MM-DD');
end;

测试:

SQL> alter session set nls_date_format = 'YYYY-MM-DD';

Session altered.

SQL> declare
  2     function my_to_date (p_str varchar2) return date
  3     is
  4     begin
  5        return to_date (p_str, 'DD/MM/YYYY');
  6     exception
  7        when others then
  8           return to_date (p_str, 'YYYY-MM-DD');
  9     end;
 10  begin
 11     dbms_output.put_line(my_to_date('29-DEC-1999'));
 12     dbms_output.put_line(my_to_date('30/12/1999'));
 13     dbms_output.put_line(my_to_date('1999-12-31'));
 14  end;
 15  /
1999-12-29
1999-12-30
1999-12-31

PL/SQL procedure successfully completed.