Count months between two timestamp on postgresql?

前端 未结 11 1364
一个人的身影
一个人的身影 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:10

    If you will do this multiple times, you could define the following function:

    CREATE FUNCTION months_between (t_start timestamp, t_end timestamp)
        RETURNS integer
        AS $$
            SELECT
                (
                    12 * extract('years' from a.i) + extract('months' from a.i)
                )::integer
            from (
                values (justify_interval($2 - $1))
            ) as a (i)
        $$
        LANGUAGE SQL
        IMMUTABLE
        RETURNS NULL ON NULL INPUT;
    

    so that you can then just

    SELECT months_between('2015-01-01', now());
    

提交回复
热议问题