TIME Arithmetic Wraps Past Midnight

Adding or subtracting an interval from a time wraps on the 24-hour scale: 22:00 plus 8 hours is 06:00, and time values alone cannot say which day.

SqlData Integrity

Code

snippet
-- TIME(time without time zone)加减 interval:跨 24:00 循环回绕
SELECT
    TIME '22:00' + INTERVAL '8 hours'    AS shift_end,    -- 06:00:00,回绕到次日钟点
    TIME '00:30' - INTERVAL '2 hours'    AS back,         -- 22:30:00,回绕到前一晚
    TIME '09:00' + INTERVAL '90 minutes' AS meeting_end;  -- 10:30:00

-- 回绕是 time 类型的文档语义:结果按 24 小时刻度取模
-- 对比:timestamp 加 interval 会推进日期,不回绕
SELECT TIMESTAMP '2026-06-21 22:00' + INTERVAL '8 hours' AS ts_advances; -- 次日 06:00

-- 排班场景:夜班跨午夜,两个 time 无法表达"次日凌晨"
SELECT TIME '22:00' < TIME '06:00' AS same_day_compare;  -- false:time 只有钟点,没有日期

-- 正确表达夜班:日期 + 时间组合成完整时间戳,先后次序才有全局意义
SELECT DATE '2026-06-21' + TIME '22:00' AS shift_start,
       DATE '2026-06-22' + TIME '06:00' AS shift_end_next_morning;

What happens when it runs

The file runs SELECT statements.

Adding INTERVAL '8 hours' to TIME '22:00' lands on 06:00:00 because a time value carries clock ticks only — the result is taken modulo the 24-hour scale, and there is no date component to advance. The comparison TIME '22:00' < TIME '06:00' returns false for the same reason: bare clock values cannot say which day each belongs to, so a night shift that crosses midnight cannot be ordered with time alone. The closing statement builds that ordering by pairing DATE '2026-06-21' with TIME '22:00' and DATE '2026-06-22' with TIME '06:00', while the TIMESTAMP line shows the contrasting behavior — the same 8-hour interval advances the date instead of wrapping.

Key statements

SELECT
    TIME '22:00' + INTERVAL '8 hours'    AS shift_end,    -- 06:00:00,回绕到次日钟点
    TIME '00:30' - INTERVAL '2 hours'    AS back,         -- 22:30:00,回绕到前一晚
    TIME '09:00' + INTERVAL '90 minutes' AS meeting_end;  -- 10:30:00
SELECT DATE '2026-06-21' + TIME '22:00' AS shift_start,
       DATE '2026-06-22' + TIME '06:00' AS shift_end_next_morning;
SELECT TIMESTAMP '2026-06-21 22:00' + INTERVAL '8 hours' AS ts_advances; -- 次日 06:00

Interactive Tools for This Topic