OffsetDateTime Stamps API Payloads

Stamp API payloads with fixed-offset OffsetDateTime and parse ISO-8601 back, comparing instants instead of strings across offsets.

JavaData Fetching

Code

snippet
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class ApiTimestamp {

    public static void main(String[] args) {
        // 固定偏移的 OffsetDateTime:不带时区规则,序列化后语义稳定
        OffsetDateTime stamped =
                OffsetDateTime.of(2026, 11, 15, 9, 30, 0, 0, ZoneOffset.UTC);
        System.out.println(stamped.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));

        // 解析上游字符串:+02:00 与 UTC 表示的可能是同一时刻
        OffsetDateTime inbound = OffsetDateTime.parse("2026-11-15T11:30+02:00");
        System.out.println("same instant: " + inbound.toInstant().equals(stamped.toInstant()));
        System.out.println(inbound);
    }
}

Stamping with a fixed offset

OffsetDateTime.of(2026, 11, 15, 9, 30, 0, 0, ZoneOffset.UTC) carries an explicit offset rather than region rules, so serializing with DateTimeFormatter.ISO_OFFSET_DATE_TIME yields the stable 2026-11-15T09:30Z string.

Parsing inbound offsets

OffsetDateTime.parse(“2026-11-15T11:30+02:00”) accepts a different offset; comparing instants with toInstant().equals(…) prints same instant: true because 11:30+02:00 is the same moment as 09:30Z — string comparison would have said otherwise.

Why instants for comparison

Two timestamps written against different offsets denote the same point on the timeline only after normalization; toInstant() performs that normalization and is the correct equality basis.

FAQ

Why prefer OffsetDateTime for API payloads?
A fixed offset serializes deterministically and stays readable at both ends, avoiding zone-rule drift across services.
How do you compare two timestamps written with different offsets?
Convert both with toInstant() and compare the instants; string or local-time comparison would misjudge the same moment.