How do you do date math that ignores the year?

前端 未结 8 1674
梦谈多话
梦谈多话 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:49

    How about this?

    select *
    from events e
    where to_char(e."date", 'MM-DD') between to_char(now(), 'MM-DD') and 
                                             to_char(date(now())+14, 'MM-DD')
    

    You can do the comparison as strings.

    To take year ends into account, we'll convert back to dates:

    select *
    from events e
    where to_date(to_char(now(), 'YYYY')||'-'||to_char(e."date", 'MM-DD'), 'YYYY-MM-DD')
               between date(now()) and date(now())+14
    

    You do need to make a slight adjustment for Feb 29. I might suggest:

    select *
    from (select e.*,
                 to_char(e."date", 'MM-DD') as MMDD
          from events
         ) e
    where to_date(to_char(now(), 'YYYY')||'-'||(case when MMDD = '02-29' then '02-28' else MMDD), 'YYYY-MM-DD')
               between date(now()) and date(now())+14
    

提交回复
热议问题