Date between dates, ignore year Date between dates, ignore year mysql mysql

Date between dates, ignore year


Use the DayOfYear function:

 SELECT foo FROM dates WHERE DayOfYear('2014-05-05')     BETWEEN DayOfYear(`since`) AND DayOfYear(`upto`)


SELECT foo FROM dates WHERE DATE_FORMAT('2014-01-15', "%m-%d")     BETWEEN DATE_FORMAT(`since`,"%m-%d") AND DATE_FORMAT(`upto`,"%m-%d")

Here's the SQL FIDDLE demo


Since you indicated that you're fine storing an arbitrary year in your data, then you can keep using a DATE type. Then it just comes down to how to query.

  • Store the fields using a fixed arbitrary year. You should use a leap-year to accommodate the possibility of Feb 29th values. Year 2000 works nicely. (0004 won't work because it's too small for MySQL's Date type.)

  • Replace the year of any value you're querying with the same year.

  • Consider ranges that cross over the end of one year and into the next. To fully answer that, you'll need a query such as the following:

    SET @dt = cast(CONCAT('2000',RIGHT(thesourcedatevalue,6)) as DATE);SELECT some_column FROM datesWHERE (since <= upto AND since <= @dt AND upto >= @dt) OR      (since > upto AND (since <= @dt OR upto >= @dt))

    Here is a SQL Fiddle that demonstrates

  • For performance, you should be sure that there is an index that includes the since and upto fields.