timestamp.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. /** ISO-shaped time-context timestamp formatting shared by production and replay validation. */
  2. type TimestampPart = 'day' | 'hour' | 'minute' | 'month' | 'second' | 'timeZoneName' | 'year'
  3. /**
  4. * Create the exact formatter used by durable time-context readings.
  5. * @param timeZone - Explicit display zone, or `undefined` for the process fallback.
  6. * @returns A formatter with stable numeric local fields and long numeric offset.
  7. */
  8. export function createTimestampFormatter(timeZone?: string): Intl.DateTimeFormat {
  9. return new Intl.DateTimeFormat('en-US', {
  10. ...(timeZone === undefined ? {} : { timeZone }),
  11. year: 'numeric',
  12. month: '2-digit',
  13. day: '2-digit',
  14. hour: '2-digit',
  15. minute: '2-digit',
  16. second: '2-digit',
  17. hourCycle: 'h23',
  18. timeZoneName: 'longOffset',
  19. })
  20. }
  21. /**
  22. * Format an epoch millisecond value as an ISO-shaped timestamp with offset and IANA zone.
  23. * @param now - Epoch milliseconds to display.
  24. * @param formatter - Formatter created for `timeZone`.
  25. * @param timeZone - Canonical zone label carried in brackets.
  26. * @returns The durable timestamp text.
  27. */
  28. export function formatTimestamp(now: number, formatter: Intl.DateTimeFormat, timeZone: string): string {
  29. const parts = Object.fromEntries(
  30. formatter.formatToParts(now).map(part => [part.type, part.value]),
  31. ) as Record<TimestampPart, string>
  32. const offset = parts.timeZoneName.replace(/^GMT$/, 'GMT+00:00').slice(3)
  33. return `${parts['year']}-${parts['month']}-${parts['day']}T${parts['hour']}:${parts['minute']}:${parts['second']}${offset}[${timeZone}]`
  34. }