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.
Code
-- 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
Age CalculatorCalculate exact age in years, months, and days between a birth date and a reference date, plus total days and the next birthday countdown.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Business Days CalculatorCount the weekdays between two dates, excluding weekends and any holidays you list, and see how many calendar and weekend days are involved.
FAQ
- Name the tables involved in this file.
- `age`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.