All files / src/util time.tsx

92.3% Statements 24/26
94.44% Branches 17/18
100% Functions 5/5
95.45% Lines 21/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87  30x                       119x   119x                                                 6035x 6003x 6003x 235x   5768x 5768x 5747x             50x 4x 4x           4x         160x 160x   160x               160x 160x 348x 160x          
export function formatLocalDate(date: Date): string {
  return date.toLocaleString("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    // second: "2-digit",
    timeZoneName: "short", // shows BST or GMT
  });
}
 
/** An ISO date-time with no zone: "2026-09-24T10:00:00", optionally ".123456". */
const NAIVE_ISO_DATETIME = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/;
/** A calendar date with no time: "2026-09-24". */
const ISO_DATE_ONLY = /^(\d{4})-(\d{2})-(\d{2})$/;
 
/**
 * Any timestamp the backends send, as a Date in the viewer's own timezone.
 *
 * **Every server timestamp must be read through this, never `new Date(str)`**
 * (the hygiene test enforces it). svc-core and svc-ai store naive UTC. Their
 * API responses now carry "+00:00" (docs/system/data/timestamps.md), but
 * values inside stored JSON — edit-history snapshots, older experiment config
 * — still arrive with no zone ("2026-09-24T10:00:00"), and `new Date` reads a
 * zone-less date-time as *local* time: every time shown off by the viewer's
 * UTC offset, and "5 minutes ago" becoming "an hour from now" in summer.
 *
 * - naive ISO date-time → read as UTC
 * - a value with a zone ("…Z", "…+00:00" — svc-auth, JSON metadata, RSS's
 *   "…GMT") → as given
 * - a bare date ("2026-09-24") → that calendar day, local midnight. `new
 *   Date` would read it as UTC midnight, which is the day before anywhere
 *   west of Greenwich.
 */
export function parseServerDate(value: string): Date {
  // Much of the data reaching here is typed `any` (react-query's `data`
  // under the pinned TypeScript), so a missing field can arrive as undefined
  // despite the signature. Behave as `new Date` did — an Invalid Date — rather
  // than throw on `.trim()` and take the page down.
  if (typeof value !== "string") return new Date(value as unknown as number);
  const trimmed = value.trim();
  if (NAIVE_ISO_DATETIME.test(trimmed)) {
    return new Date(`${trimmed.replace(" ", "T")}Z`);
  }
  const day = ISO_DATE_ONLY.exec(trimmed);
  if (day) return new Date(+day[1], +day[2] - 1, +day[3]);
  return new Date(trimmed);
}
 
/** `parseServerDate` for optional fields: null for absent or unreadable. */
export function parseServerDateOrNull(
  value: string | null | undefined,
): Date | null {
  if (!value) return null;
  const date = parseServerDate(value);
  return Number.isNaN(date.getTime()) ? null : date;
}
 
/** Milliseconds since the epoch for a server timestamp — for sorting and
 *  bucketing. NaN for an unreadable value, as `Date.getTime` gives. */
export function serverTime(value: string | null | undefined): number {
  return value ? parseServerDate(value).getTime() : NaN;
}
 
/** Short, human-friendly relative time, e.g. "just now", "5m ago", "3d ago". */
export function timeAgo(date: Date): string {
  const seconds = Math.round((Date.now() - date.getTime()) / 1000);
  Iif (seconds < 45) return "just now";
 
  const units: [Intl.RelativeTimeFormatUnit, number][] = [
    ["year", 60 * 60 * 24 * 365],
    ["month", 60 * 60 * 24 * 30],
    ["day", 60 * 60 * 24],
    ["hour", 60 * 60],
    ["minute", 60],
    ["second", 1],
  ];
  const rtf = new Intl.RelativeTimeFormat(undefined, { numeric: "auto" });
  for (const [unit, secondsInUnit] of units) {
    if (seconds >= secondsInUnit || unit === "second") {
      return rtf.format(-Math.floor(seconds / secondsInUnit), unit);
    }
  }
  return "just now";
}