| Need to convert into date for differernt kind of formates [message #647276] |
Mon, 25 January 2016 04:16  |
 |
saipradyumn
Messages: 419 Registered: October 2011 Location: Hyderabad
|
Senior Member |
|
|
Hi
Please help me to convert into date for the folloinwg inut character formates by using regular expression .
with data as
(select 'August 2015' v
from dual
union all
select '2014 may' v
from dual
union all
select 'June 2013' v from dual
)
select * from data
|
|
|
|
|
|
| Re: Need to convert into date for differernt kind of formates [message #647300 is a reply to message #647276] |
Mon, 25 January 2016 14:04   |
 |
Barbara Boehmer
Messages: 9106 Registered: November 2002 Location: California, USA
|
Senior Member |
|
|
The first thing that comes to mind is why you have data in various formats. If this is user input, then the input should be restricted to one format and clearly labeled. If this is some unformatted legacy data, then you do what you can with it. It is impossible to account for all possible formats, as, for example, there is no way to tell if 01-02-2016 is January second or the first of February. If you have a limited number of formats, then you can write a function to test for them. In the following example, the fix_date function first attempts to apply the to_date function using your most common format. If that format fails, then it tries the other one. If it fails both, then it returns null. You could modify it to attempt various other formats. The following also only uses one language, but you could modify it to use others. You can then insert your date into a date column, or display it in any format you wish using to_char.
SCOTT@orcl> create or replace function fix_date
2 (p_string in varchar2)
3 return date
4 as
5 v_date date;
6 e_invalid_month exception;
7 pragma exception_init (e_invalid_month, -01843);
8 begin
9 begin
10 v_date := to_date (lower (p_string), 'month yyyy', 'NLS_DATE_LANGUAGE = American');
11 exception
12 when e_invalid_month then
13 begin
14 v_date := to_date (lower (p_string), 'yyyy mon', 'NLS_DATE_LANGUAGE = American');
15 exception
16 when others then
17 v_date := to_date (null);
18 end;
19 when others then
20 v_date := to_date (null);
21 end;
22 return v_date;
23 end fix_date;
24 /
Function created.
SCOTT@orcl> show errors
No errors.
SCOTT@orcl> with data as
2 (select 'August 2015' v
3 from dual
4 union all
5 select '2014 may' v
6 from dual
7 union all
8 select 'June 2013' v from dual
9 )
10 select to_char (fix_date (v), 'dy dd-mon-yyyy') fixed_date from data
11 /
FIXED_DATE
---------------------------------
sat 01-aug-2015
thu 01-may-2014
sat 01-jun-2013
3 rows selected.
[Updated on: Mon, 25 January 2016 14:07] Report message to a moderator
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|