Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Month and day comparison in Oracle

How do you compare month and day together in datetime operations in Oracle?

Assume, currentdate as = 15 Aug 2014 (in datetime format).

I have to compare currentdate (excluding year) with 2 different static dates excluding year, e.g.

Filter as - 15/Aug between 01/Jul and 20/Dec.

I think for the above to work we need to extract day and month together in datetime format. Please suggest answers. Thanks.

like image 770
user3790670 Avatar asked Jul 11 '14 14:07

user3790670


People also ask

Can we compare 2 dates in Oracle?

You can use "classic comparators" (like >, >=, <, =...) to compare 2 dates. If you have date data types : don't convert them. if you have no choice, use something like: if to_char(d1,'YYYYMMDD') > to_char(d2,'YYYYMMDD') then ... else ...

What is the difference between Rrrr and YYYY in Oracle?

Hi, YYYY gives the current year as 4 digits. RRRR format means 2-digit years in the range 00 to 49 are assumed to be in the current century (ie have the same first two digits as the current year), and years given as 50 through 99 are assumed to be in the previous century.

How can I calculate months between two dates in Oracle?

MONTHS_BETWEEN returns number of months between dates date1 and date2 . If date1 is later than date2 , then the result is positive. If date1 is earlier than date2 , then the result is negative. If date1 and date2 are either the same days of the month or both last days of months, then the result is always an integer.

How do I display a date in YYYY MM DD format in Oracle?

Use TO_CHAR to display it in any format you like. For example: SELECT TO_CHAR ( TO_DATE (date_value, 'yyyy-mm-dd') , 'mm/dd/yyyy' ) FROM table_x; Things are much easier if you store dates in DATE columns.


2 Answers

You can use the TO_CHAR function to convert the date to text and then compare.

SELECT *
FROM mytable
WHERE TO_CHAR(SYSDATE, 'MMDD') BETWEEN TO_CHAR(start_date, 'MMDD') AND TO_CHAR(end_date, 'MMDD');

The BETWEEN operator is inclusive of the limits. If you do not want to include the limits, you can use:

SELECT *
FROM mytable
WHERE TO_CHAR(SYSDATE, 'MMDD') > TO_CHAR(start_date, 'MMDD') 
AND TO_CHAR(SYSDATE, 'MMDD') < TO_CHAR(end_date, 'MMDD');
like image 63
Joseph B Avatar answered Oct 04 '22 02:10

Joseph B


Simply use to_char to get month and day (both as two-digit values) concatenated, then use between:

select *
from mytable
where to_char(mydate,'mmdd') between '0815' and '1220';
like image 28
Thorsten Kettner Avatar answered Oct 04 '22 03:10

Thorsten Kettner