ISO 8601 Interval String Cast

Interval literals accept both verbose strings and ISO 8601 durations like P1DT2H, and the two forms compare equal for the same span.

SqlData Integrity

Code

snippet
-- interval 字面量两种写法:verbose 与 ISO 8601 duration
SELECT
    INTERVAL '2 years 3 months 10 days' AS verbose_form,
    INTERVAL 'P2Y3M10D'                 AS iso_duration,       -- P..Y..M..D
    INTERVAL 'P1DT2H30M'                AS iso_with_time,      -- T 后是时分秒
    INTERVAL 'PT90S'                    AS iso_seconds_only;   -- 90 秒

-- 同一时长两种写法相等,可直接比较
SELECT INTERVAL 'P1DT2H' = INTERVAL '1 day 2 hours' AS iso_equals_verbose;  -- true

-- API 输入常用 ISO 8601 duration:直接 cast 即可参与时间运算
SELECT 'P3DT4H'::interval + TIMESTAMP '2026-11-19 08:00' AS starts_at;

-- duration 里 day/hour 是独立字段,可按需 extract
SELECT EXTRACT(DAY  FROM INTERVAL 'P3DT4H') AS days,    -- 3
       EXTRACT(HOUR FROM INTERVAL 'P3DT4H') AS hours;   -- 4

Inside the snippet

Four INTERVAL literals are selected side by side: the verbose 2 years 3 months 10 days next to three ISO 8601 durations — P2Y3M10D, P1DT2H30M and seconds-only PT90S — so both notations sit in one result row for direct comparison.

Putting it to use

INTERVAL 'P1DT2H' = INTERVAL '1 day 2 hours' evaluates to true, confirming the same span parses identically in either notation. API input shaped as an ISO 8601 duration needs no rewriting: 'P3DT4H'::interval casts it in place, and the cast value adds straight onto TIMESTAMP '2026-11-19 08:00' to produce starts_at. The day and hour fields stay independently readable — EXTRACT(DAY FROM INTERVAL 'P3DT4H') returns 3, and EXTRACT(HOUR FROM ...) returns 4.

Key statements

SELECT 'P3DT4H'::interval + TIMESTAMP '2026-11-19 08:00' AS starts_at;

Interactive Tools for This Topic

FAQ

Which relations are involved here?
`interval`.