Count months between two timestamp on postgresql?

前端 未结 11 1293
一个人的身影
一个人的身影 2021-02-01 14:50

I want to count the number of months between two dates.

Doing :

SELECT TIMESTAMP \'2012-06-13 10:38:40\' - TIMESTAMP \'2011-04-30 14:38:40\';
         


        
11条回答
  •  甜味超标
    2021-02-01 15:36

    Please note that the most voted answer by @ram and @angelin is not accurate when you are trying to get calendar month difference using.

    select extract(year from age(timestamp1, timestamp2))*12 + extract(month from age(timestamp1, timestamp2))
    

    for example, if you try to do:

    select extract(year from age('2018-02-02'::date, '2018-03-01'::date))*12 + extract(month from age('2018-02-02'::date , '2018-03-01'::date))
    

    the result will be 0 but in terms of months between March from February should be 1 no matter the days between dates.

    so the formula should be like the following saying that we start with timestamp1 and timestamp2:

    ((year2 - year1)*12) - month1 + month2 = calendar months between two timestamps

    in pg that would be translated to:

    select ((extract('years' from '2018-03-01 00:00:00'::timestamp)::int -  extract('years' from '2018-02-02 00:00:00'::timestamp)::int) * 12) 
        - extract('month' from '2018-02-02 00:00:00'::timestamp)::int + extract('month' from '2018-03-01 00:00:00'::timestamp)::int;
    

    you can create a function like:

    CREATE FUNCTION months_between (t_start timestamp, t_end timestamp)
    RETURNS integer
    AS $$
    select ((extract('years' from $2)::int -  extract('years' from $1)::int) * 12) 
        - extract('month' from $1)::int + extract('month' from $2)::int
    $$
    LANGUAGE SQL
    IMMUTABLE
    RETURNS NULL ON NULL INPUT;
    

提交回复
热议问题