Difference between two dates in postgresql

后端 未结 1 948
鱼传尺愫
鱼传尺愫 2021-01-24 00:07

Function:

CREATE FUNCTION diff(d1 date,d2 date) RETURNS int AS $$
BEGIN
IF d1 = NULL THEN
RETURN SELECT extract(year from age(current_date,d2));
ELSE
RETURN SELE         


        
相关标签:
1条回答
  • 2021-01-24 00:35

    Try :

    date_part('year',age(coalesce(d1,current_date), d2))::int;
    

    age(d1,d2) function returns the number of years, months, and days between two dates in following format:

    xxx year(s) xxx mon(s) xxx day(s).
    

    from this output using date_part() to pick the only the year difference. and also no need to put if statement to handle NULL as I have added coalesece which returns first NON Null value, So if d1 is NULL it return cuurent_date

    Function Structure:

    CREATE OR REPLACE FUNCTION diff(d1 date,d2 date) RETURNS int AS $$
    BEGIN
    
     RETURN date_part('year',age(coalesce(d1,current_date), d2))::int;
    END
    $$ language plpgsql;
    

    Function Call:

    select * from diff(null,'2010-04-01');
    select * from diff('2012-10-01','2010-04-01');
    
    0 讨论(0)
提交回复
热议问题