How to write the code in Oracle SQL
(like \'CCYYMMDD\'
into 102
)?
If someone will enter the date in the frontend, the value should return
You cannot write a function to determine which numeric date string corresponds to which format as the date string could be multiple formats:
For example, 010203
could be:
DDMMYY
1st February 03MMDDYY
2nd January 03YYMMDD
3rd February 01DDHHMM
02:03 of Day 1HHMMSS
01:02:03MMMMSS
102 minutes 3 secondsCCYYMM
March 0102CCYYWW
Week 3 of 0102Similarly 10080102
could be:
DDMMCCYY
10th August 102CCYYMMDD
2nd January 1008MMDDHHMM
8th October 01:02HHMMHHMM
Time span from 10:08 to 01:01If anyone inserts the date in this format "CCYYMMDD" then the value should return only 102 as a default in the frontend. How to write the code in SQL?
You cannot, as I described above it is ambiguous what some values are and they could return multiple formats. Instead you should create another column and store the date format in that when the user inputs the date rather than trying to reconstruct the format code from an (ambiguous) number.
You can verify that a string fits a date format like this:
create or replace function is_CCYYMMDD
(p_str in varchar2)
return boolean
is
rv boolean;
dt date;
begin
begin
dt := to_date(p_str, 'YYYYMMDD');
dt := to_date('2000' || substr(p_str, 5), 'YYYYMMDD');
rv := true;
exception
when others then
rv := false;
end;
return rv;
end;
The first to_date()
just checks that the whole string is a valid date. The second to_date()
checks that the second half of the string is a valid month and day combo. This partly addresses @MTO observations about the problems of enforcing a strict format when some strings can fit more than one format.
Note that it is perfectly possible to have valid dates which pass this test despite being ambiguous e.g. is 20111012
in 'YYYYMMDD'
or 'DDMMYYYY'
? There is no way to be sure unless you enforce strict date formatting in the front-end input by using a date picker widget or separate input boxes for year, month and day.
why you pass '2000' in this query?
The second check verifies that the last four characters are valid as month and day. Whenever we do this sort of test we run into the problem of leap years. If we just apply to_date(str, 'MMDD')
Oracle will default the year to the current year: the snag is 2018029
is not a valid date even though the original input of 20160229
is valid. My function avoids this by fixing the year element to 2000, which was a leap year.
Incidentally, if you want to use this function in SQL you'll need to change the return datatype to varchar2 (Y/N flag) or a number (1/0) because SQL doesn't support Booolean.
If you want to convert an Oracle date into a Julian date, then you can use the TO_CHAR function with 'j' as the format.
SELECT TO_CHAR(TO_DATE('BC47120412', 'BCYYYYMMDD'), 'J')
FROM DUAL;
Output: 0000102
If you want to convert julian date to oracle date then use query below,
SELECT TO_DATE(102, 'J')
FROM DUAL;
Output: 04/12/4712 12:00:00 AM BC