PostgreSQL: days/months/years between two dates

后端 未结 10 1992
旧时难觅i
旧时难觅i 2020-12-12 20:22

I am looking for a way to implement the SQLServer-function datediff in PostgreSQL. That is,

This function returns the count (as a signed integer valu

10条回答
  •  借酒劲吻你
    2020-12-12 20:33

    Almost the same function as you needed (based on atiruz's answer, shortened version of UDF from here)

    CREATE OR REPLACE FUNCTION datediff(type VARCHAR, date_from DATE, date_to DATE) RETURNS INTEGER LANGUAGE plpgsql
    AS
    $$
    DECLARE age INTERVAL;
    BEGIN
        CASE type
            WHEN 'year' THEN
                RETURN date_part('year', date_to) - date_part('year', date_from);
            WHEN 'month' THEN
                age := age(date_to, date_from);
                RETURN date_part('year', age) * 12 + date_part('month', age);
            ELSE
                RETURN (date_to - date_from)::int;
        END CASE;
    END;
    $$;
    

    Usage:

    /* Get months count between two dates */
    SELECT datediff('month', '2015-02-14'::date, '2016-01-03'::date);
    /* Result: 10 */
    
    /* Get years count between two dates */
    SELECT datediff('year', '2015-02-14'::date, '2016-01-03'::date);
    /* Result: 1 */
    
    /* Get days count between two dates */
    SELECT datediff('day', '2015-02-14'::date, '2016-01-03'::date);
    /* Result: 323 */
    
    /* Get months count between specified and current date */
    SELECT datediff('month', '2015-02-14'::date, NOW()::date);
    /* Result: 47 */
    

提交回复
热议问题