AGE Calendar Aware Interval Difference

Compute year/month/day gaps with age(), which borrows calendar days across month ends instead of assuming fixed-length months.

SqlData Integrity

Code

snippet
-- age(end, start):calendar-aware 年/月/日差,不是固定换算成天数
SELECT
    age(TIMESTAMP '2026-11-19', TIMESTAMP '2024-09-30') AS tenure,
    -- 月末借位:1 月 31 日到 3 月 31 日正好两个整月
    age(TIMESTAMP '2026-03-31', TIMESTAMP '2026-01-31') AS month_end_span,
    -- 单参数重载:以 current_date 为基准
    age(TIMESTAMP '2026-01-01') AS since_new_year;

-- 只需要总天数时直接相减:date 减 date 返回整数天
SELECT DATE '2026-11-19' - DATE '2024-09-30' AS total_days;

-- age 返回 interval,可以再 extract 出单个字段
SELECT
    EXTRACT(YEAR  FROM age(TIMESTAMP '2026-11-19', TIMESTAMP '2024-09-30')) AS years,
    EXTRACT(MONTH FROM age(TIMESTAMP '2026-11-19', TIMESTAMP '2024-09-30')) AS months,
    EXTRACT(DAY   FROM age(TIMESTAMP '2026-11-19', TIMESTAMP '2024-09-30')) AS days;

How the snippet works

The file runs SELECT statements, touching age.

Applying it

Run the statement against the age table.

The statements worth quoting

SELECT
    EXTRACT(YEAR  FROM age(TIMESTAMP '2026-11-19', TIMESTAMP '2024-09-30')) AS years,
    EXTRACT(MONTH FROM age(TIMESTAMP '2026-11-19', TIMESTAMP '2024-09-30')) AS months,
    EXTRACT(DAY   FROM age(TIMESTAMP '2026-11-19', TIMESTAMP '2024-09-30')) AS days;
SELECT
    age(TIMESTAMP '2026-11-19', TIMESTAMP '2024-09-30') AS tenure,
    age(TIMESTAMP '2026-03-31', TIMESTAMP '2026-01-31') AS month_end_span,
    age(TIMESTAMP '2026-01-01') AS since_new_year;
SELECT DATE '2026-11-19' - DATE '2024-09-30' AS total_days;

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
`age`.