paulund

9. Datetime Handling

9. Datetime Handling

Datetime fields are a surprisingly common source of bugs in API integrations. Agreeing on a single format and sticking to it eliminates the ambiguity that causes those bugs.

Use ISO 8601 in UTC

Every datetime value your API returns or accepts should be in ISO 8601 format with a Z suffix indicating UTC:

YYYY-MM-DDTHH:MM:SSZ

Concrete examples:

2026-08-16T12:34:56Z
2026-01-01T00:00:00Z

Guidelines

  • Always store and transmit in UTC. Let the client convert to the user's local timezone for display. This keeps your server-side logic simple and your data consistent regardless of where requests originate.
  • Include seconds. Omitting them invites parsing inconsistencies. Add milliseconds only when your application genuinely requires sub-second precision: 2026-08-16T12:34:56.123Z.
  • Avoid the +0000 offset variant. Some languages (notably PHP's DATE_ISO8601 constant) produce 2026-08-16T12:34:56+0000 instead of the correct 2026-08-16T12:34:56+00:00. The missing colon in the offset breaks strict ISO 8601 parsers. Use the Z suffix instead.
  • Normalise offsets in query parameters. If a client sends ?after=2026-08-16T12:00:00+01:00, convert it to UTC internally before querying your database. Do not store raw offset strings.

Why This Matters

  • Consistent ordering and comparisons. UTC timestamps sort lexicographically, which means string comparison and chronological comparison produce the same result.
  • Simpler storage. A single timezone across all rows eliminates the class of bugs where a timestamp stored as +01:00 in one row and +05:30 in another produces incorrect relative ordering.
  • Fewer timezone bugs. Timezone conversion is error-prone. Doing it once, at the client boundary, keeps the rest of your system free from that complexity.