How do you do date math that ignores the year?

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

    For convenience, I created two functions that yield the (expected or past) birsthday in the current year, and the upcoming birthday.

    CREATE OR REPLACE FUNCTION this_years_birthday( _dut DATE) RETURNS DATE AS
    $func$
    
    DECLARE
            ret DATE;
    BEGIN
            ret =
            date_trunc( 'year' , current_timestamp)
            + (date_trunc( 'day' , _dut)
              - date_trunc( 'year' , _dut)
              )
            ;
            RETURN ret;
    END;
    $func$ LANGUAGE plpgsql;
    
    CREATE OR REPLACE FUNCTION next_birthday( _dut DATE) RETURNS DATE AS
    $func$
    
    DECLARE
            ret DATE;
    BEGIN
            ret =
            date_trunc( 'year' , current_timestamp)
            + (date_trunc( 'day' , _dut)
              - date_trunc( 'year' , _dut)
              )
            ;
            IF (ret < date_trunc( 'day' , current_timestamp))
               THEN ret = ret + '1year'::interval; END IF;
            RETURN ret;
    END;
    $func$ LANGUAGE plpgsql;
    
          --
          -- call the function
          --
    SELECT date_trunc( 'day' , t.topic_date) AS the_date
            , this_years_birthday( t.topic_date::date ) AS the_day
            , next_birthday( t.topic_date::date ) AS next_day
    FROM topic t
    WHERE this_years_birthday( t.topic_date::date )
            BETWEEN  current_date
            AND  current_date + '2weeks':: interval
            ;
    

    NOTE: the casts are needed because I only had timestamps available.

提交回复
热议问题