How do you do date math that ignores the year?

前端 未结 8 1703
梦谈多话
梦谈多话 2020-11-28 11:14

I am trying to select dates that have an anniversary in the next 14 days. How can I select based on dates excluding the year? I have tried something like the following.

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 11:59

    I believe the following test works in all cases, assuming a column named anniv_date:

    select * from events
    where extract(month from age(current_date+interval '14 days', anniv_date))=0
      and extract(day from age(current_date+interval '14 days', anniv_date)) <= 14
    

    As an example of how it works when crossing a year (and also a month), let's say an anniversary date is 2009-01-04 and the date at which the test is run is 2012-12-29.

    We want to consider any date between 2012-12-29 and 2013-01-12 (14 days)

    age('2013-01-12'::date, '2009-01-04'::date) is 4 years 8 days.

    extract(month...) from this is 0 and extract(days...) is 8, which is lower than 14 so it matches.

提交回复
热议问题