Skip to content

Modern Docker Management, Designed for Everyone

refactor: use native temporal for time/date parsing (#3714)

Kyle Mendell60c2dee13cd9
diff --git a/frontend/package.json b/frontend/package.json
index 20d42ab86..be2849aeb 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -47,7 +47,6 @@
"ansi-to-html": "^0.7.2",
"bits-ui": "^2.18.1",
"clsx": "^2.1.1",
- "date-fns": "^4.4.0",
"embla-carousel-svelte": "^8.6.0",
"formsnap": "^2.0.1",
"ky": "^2.0.2",
@@ -60,6 +59,7 @@
"svelte-sonner": "^1.2.1",
"tailwind-merge": "^3.6.0",
"tailwind-variants": "^3.3.1",
+ "temporal-polyfill": "^1.0.4",
"vaul-svelte": "1.0.0-next.7",
"yaml": "^2.9.0",
"zod": "^4.4.3"
diff --git a/frontend/src/lib/components/action-buttons.svelte b/frontend/src/lib/components/action-buttons.svelte
index 5e26814a0..a88652b09 100644
--- a/frontend/src/lib/components/action-buttons.svelte
+++ b/frontend/src/lib/components/action-buttons.svelte
@@ -27,6 +27,7 @@
import { hasPermission } from '#lib/utils/auth';
import { isDepotBuildAvailable } from '#lib/utils/build-provider';
import { environmentStore } from '#lib/stores/environment.store.svelte';
+ import { Temporal } from 'temporal-polyfill';
type TargetType = 'container' | 'project';
type LoadingStates = {
@@ -316,7 +317,7 @@
confirm: {
label: m.common_redeploy(),
action: async () => {
- const operationStartedAt = Math.floor(Date.now() / 1000);
+ const operationStartedAt = Math.floor(Temporal.Now.instant().epochMilliseconds / 1000);
if (watch) {
operationWatchStore.start(`${m.common_redeploy()} — ${name ?? id}`);
}
@@ -371,7 +372,7 @@
async function handleDeploy(options?: DeployProjectOptions, watch = false) {
setLoading('start', true);
- const operationStartedAt = Math.floor(Date.now() / 1000);
+ const operationStartedAt = Math.floor(Temporal.Now.instant().epochMilliseconds / 1000);
if (watch) {
operationWatchStore.start(`${deployButtonLabel} — ${name ?? id}`);
}
diff --git a/frontend/src/lib/components/activity/activity-completion-toasts.ts b/frontend/src/lib/components/activity/activity-completion-toasts.ts
index 561e926bd..e88245bbd 100644
--- a/frontend/src/lib/components/activity/activity-completion-toasts.ts
+++ b/frontend/src/lib/components/activity/activity-completion-toasts.ts
@@ -51,7 +51,7 @@ export function markActivityToastShown(activityId: string | undefined) {
if (!activityId) {
return;
}
- const now = Date.now();
+ const now = performance.now();
for (const [id, shownAt] of shownActivityIds) {
if (now - shownAt > SHOWN_SUPPRESSION_MS) {
shownActivityIds.delete(id);
@@ -62,7 +62,7 @@ export function markActivityToastShown(activityId: string | undefined) {
function wasToastShownInternal(activityId: string): boolean {
const shownAt = shownActivityIds.get(activityId);
- return shownAt !== undefined && Date.now() - shownAt <= SHOWN_SUPPRESSION_MS;
+ return shownAt !== undefined && performance.now() - shownAt <= SHOWN_SUPPRESSION_MS;
}
export function queueActivityCompletionToast(activity: Activity) {
diff --git a/frontend/src/lib/components/activity/activity-detail-panel.svelte b/frontend/src/lib/components/activity/activity-detail-panel.svelte
index 504be2945..db6e6c246 100644
--- a/frontend/src/lib/components/activity/activity-detail-panel.svelte
+++ b/frontend/src/lib/components/activity/activity-detail-panel.svelte
@@ -9,7 +9,8 @@
import ActivityOutput from './activity-output.svelte';
import { confirmCancelActivity } from './activity-cancel';
import { activityStatusLabel, activityStatusVariant, activityTypeIcon, activityTypeLabel } from './activity-labels';
- import { formatDateTime } from '#lib/utils/formatting';
+ import { formatDateTime, parseInstant } from '#lib/utils/formatting';
+ import { Temporal } from 'temporal-polyfill';
let { activity }: { activity: Activity } = $props();
@@ -35,13 +36,14 @@
return m.common_na();
}
return formatDateTime(value, {
- datePattern: 'MMM d,',
+ dateStyle: 'month-day',
includeSeconds: true
});
}
function formatDurationInternal(value: Activity | null): string {
- const durationMs = value?.durationMs ?? (value?.startedAt ? Date.now() - new Date(value.startedAt).getTime() : 0);
+ const startedAt = parseInstant(value?.startedAt);
+ const durationMs = value?.durationMs ?? (startedAt ? startedAt.until(Temporal.Now.instant()).total('milliseconds') : 0);
if (!durationMs || Number.isNaN(durationMs)) {
return m.common_na();
}
diff --git a/frontend/src/lib/components/activity/activity-list-item.svelte b/frontend/src/lib/components/activity/activity-list-item.svelte
index c8eabf43b..d9140eeb4 100644
--- a/frontend/src/lib/components/activity/activity-list-item.svelte
+++ b/frontend/src/lib/components/activity/activity-list-item.svelte
@@ -4,7 +4,7 @@
import { ArrowDownIcon } from '#lib/icons';
import { m } from '#lib/paraglide/messages';
import { cn } from '#lib/utils';
- import { formatDistanceToNow } from 'date-fns';
+ import { formatRelativeTime } from '#lib/utils/formatting';
import type { Activity, ActivityStatus } from '#lib/types/activity.type';
import { activityStatusLabel, activityStatusVariant, activityTypeIcon, activityTypeLabel } from './activity-labels';
@@ -31,7 +31,7 @@
const startedByName = $derived(activity.startedBy?.displayName || activity.startedBy?.username);
const referenceDate = $derived(activity.endedAt || activity.startedAt);
- const relativeTime = $derived(referenceDate ? formatDistanceToNow(new Date(referenceDate), { addSuffix: true }) : '');
+ const relativeTime = $derived(formatRelativeTime(referenceDate));
function statusAccentClass(status: ActivityStatus): string {
switch (status) {
diff --git a/frontend/src/lib/components/arcane-table/cells/relative-time-cell.svelte b/frontend/src/lib/components/arcane-table/cells/relative-time-cell.svelte
index 800aed415..0b256e2cd 100644
--- a/frontend/src/lib/components/arcane-table/cells/relative-time-cell.svelte
+++ b/frontend/src/lib/components/arcane-table/cells/relative-time-cell.svelte
@@ -1,25 +1,23 @@
<script lang="ts">
- import { formatDistanceToNow } from 'date-fns';
import * as ArcaneTooltip from '#lib/components/arcane-tooltip';
- import { formatDateTime } from '#lib/utils/formatting';
+ import { formatDateTime, formatRelativeTime, parseInstant } from '#lib/utils/formatting';
import { m } from '#lib/paraglide/messages';
let { value }: { value: unknown } = $props();
- const date = $derived(value ? new Date(String(value)) : null);
- const valid = $derived(!!date && !Number.isNaN(date.getTime()));
+ const instant = $derived(value ? parseInstant(String(value)) : null);
</script>
-{#if valid && date}
+{#if instant}
<ArcaneTooltip.Root>
<!-- The child snippet renders a plain span: the default trigger wrapper is
interactive and would swallow the table's row-expand click. -->
<ArcaneTooltip.Trigger>
{#snippet child({ props })}
- <span {...props} class="text-sm whitespace-nowrap">{formatDistanceToNow(date, { addSuffix: true })}</span>
+ <span {...props} class="text-sm whitespace-nowrap">{formatRelativeTime(instant)}</span>
{/snippet}
</ArcaneTooltip.Trigger>
- <ArcaneTooltip.Content>{formatDateTime(date, { includeSeconds: true })}</ArcaneTooltip.Content>
+ <ArcaneTooltip.Content>{formatDateTime(instant, { includeSeconds: true })}</ArcaneTooltip.Content>
</ArcaneTooltip.Root>
{:else}
<span class="text-sm text-muted-foreground">{m.common_na()}</span>
diff --git a/frontend/src/lib/components/arcane-table/cells/unix-created-cell.svelte b/frontend/src/lib/components/arcane-table/cells/unix-created-cell.svelte
index 5da0393fe..c6685c4b6 100644
--- a/frontend/src/lib/components/arcane-table/cells/unix-created-cell.svelte
+++ b/frontend/src/lib/components/arcane-table/cells/unix-created-cell.svelte
@@ -1,7 +1,10 @@
<script lang="ts">
import { formatDateTimeShort } from '#lib/utils/formatting';
+ import { Temporal } from 'temporal-polyfill';
let { value }: { value: unknown } = $props();
+
+ const seconds = $derived(Number(value || 0));
</script>
-{formatDateTimeShort(new Date(Number(value || 0) * 1000))}
+{Number.isFinite(seconds) ? formatDateTimeShort(Temporal.Instant.fromEpochMilliseconds(Math.trunc(seconds * 1000))) : ''}
diff --git a/frontend/src/lib/components/auth/passkey-settings.svelte b/frontend/src/lib/components/auth/passkey-settings.svelte
index 23e9e0922..0fe679491 100644
--- a/frontend/src/lib/components/auth/passkey-settings.svelte
+++ b/frontend/src/lib/components/auth/passkey-settings.svelte
@@ -4,7 +4,7 @@
startRegistration,
type PublicKeyCredentialCreationOptionsJSON
} from '@simplewebauthn/browser';
- import { format } from 'date-fns';
+ import { Temporal } from 'temporal-polyfill';
import { onMount } from 'svelte';
import { toast } from 'svelte-sonner';
import { openConfirmDialog } from '#lib/components/confirm-dialog';
@@ -13,6 +13,7 @@
import { Input } from '#lib/components/ui/input';
import * as Alert from '#lib/components/ui/alert/index.js';
import { m } from '#lib/paraglide/messages';
+ import { formatDate, parseInstant } from '#lib/utils/formatting';
import { passkeyService } from '#lib/services/passkey-service';
import type { MFAStatus, Passkey, PasskeyCapabilities, StepUpGrant } from '#lib/types/auth';
import StepUpDialog from './step-up-dialog.svelte';
@@ -36,15 +37,7 @@
// One step-up covers every management action until the grant expires, so a
// run of changes (add passkey, enable MFA, regenerate codes) prompts once.
let grantToken = $state('');
- let grantExpiresAt = $state(0);
-
- function safeFormatDate(input: string): string {
- try {
- return format(new Date(input), 'PP');
- } catch {
- return input;
- }
- }
+ let grantExpiresAt = $state<Temporal.Instant | null>(null);
function passkeyErrorDescription(value: unknown, fallback: string): string {
if (!(value instanceof Error) || !value.message.trim()) return fallback;
@@ -71,12 +64,16 @@
function clearStepUpGrant() {
grantToken = '';
- grantExpiresAt = 0;
+ grantExpiresAt = null;
}
function activeStepUpToken(): string {
// Small margin so a grant does not expire between check and request.
- return grantToken && grantExpiresAt - 5000 > Date.now() ? grantToken : '';
+ return grantToken &&
+ grantExpiresAt &&
+ Temporal.Instant.compare(grantExpiresAt.subtract({ seconds: 5 }), Temporal.Now.instant()) > 0
+ ? grantToken
+ : '';
}
async function loadAccountData(): Promise<PasskeyCapabilities | null> {
@@ -143,7 +140,7 @@
async function handleStepUpResolved(grant: StepUpGrant) {
grantToken = grant.token;
- grantExpiresAt = new Date(grant.expiresAt).getTime();
+ grantExpiresAt = parseInstant(grant.expiresAt);
const action = pendingAction;
pendingAction = null;
if (!action) return;
@@ -402,7 +399,7 @@
<div class="truncate text-sm font-medium">{passkey.name}</div>
<div class="mt-1 text-xs text-muted-foreground">
{#if passkey.lastUsedAt}
- {m.account_passkey_last_used({ date: safeFormatDate(passkey.lastUsedAt) })}
+ {m.account_passkey_last_used({ date: formatDate(passkey.lastUsedAt) || passkey.lastUsedAt })}
{:else}
{m.account_passkey_never_used()}
{/if}
diff --git a/frontend/src/lib/components/code-editor/editor.svelte b/frontend/src/lib/components/code-editor/editor.svelte
index b59abdffe..92205d1fa 100644
--- a/frontend/src/lib/components/code-editor/editor.svelte
+++ b/frontend/src/lib/components/code-editor/editor.svelte
@@ -235,11 +235,11 @@
}
function suppressSchemaHoverForSelection() {
- schemaHoverSuppressedUntil = Date.now() + schemaHoverSelectionSuppressionMs;
+ schemaHoverSuppressedUntil = performance.now() + schemaHoverSelectionSuppressionMs;
}
function isSchemaHoverSuppressed(view: EditorView): boolean {
- return hasNonEmptySelection(view) || nativeSelectionTouchesEditor(view) || Date.now() < schemaHoverSuppressedUntil;
+ return hasNonEmptySelection(view) || nativeSelectionTouchesEditor(view) || performance.now() < schemaHoverSuppressedUntil;
}
function closeActiveSchemaHoverForSelection(view: EditorView) {
diff --git a/frontend/src/lib/components/dialogs/update-all-dialog.svelte b/frontend/src/lib/components/dialogs/update-all-dialog.svelte
index 72858ff2b..47d32850e 100644
--- a/frontend/src/lib/components/dialogs/update-all-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/update-all-dialog.svelte
@@ -17,7 +17,7 @@
import BaseAPIService from '#lib/services/api-service';
import ReleaseNotes from '#lib/components/release-notes.svelte';
import type { AppVersionInformation } from '#lib/types/settings';
- import { formatDistanceToNow } from 'date-fns';
+ import { formatRelativeTime, nowInstantString } from '#lib/utils/formatting';
import VersionUpdateSummary from './version-update-summary.svelte';
// open has no $bindable fallback: upstream binds can start out undefined, and
@@ -161,10 +161,7 @@
const releaseUrl = $derived(versionInformation?.releaseUrl ?? '');
const releasedAgo = $derived.by(() => {
const at = versionInformation?.releasedAt;
- if (!at) return '';
- const date = new Date(at);
- if (Number.isNaN(date.getTime())) return '';
- return formatDistanceToNow(date, { addSuffix: true });
+ return at ? formatRelativeTime(at) : '';
});
const title = $derived.by(() => {
@@ -282,7 +279,7 @@
job = {
id: 'demo',
status: 'running',
- createdAt: new Date().toISOString(),
+ createdAt: nowInstantString(),
results: demo.map((entry, index) => ({
environmentId: index === 0 ? MANAGER_ENVIRONMENT_ID : `demo-${index}`,
environmentName: entry.name,
@@ -315,7 +312,7 @@
if (phase !== 'running' || !job) return;
job.status = 'completed';
- job.completedAt = new Date().toISOString();
+ job.completedAt = nowInstantString();
phase = 'finished';
}
</script>
diff --git a/frontend/src/lib/components/dialogs/update-center-dialog.svelte b/frontend/src/lib/components/dialogs/update-center-dialog.svelte
index c9b60e024..1fd93552d 100644
--- a/frontend/src/lib/components/dialogs/update-center-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/update-center-dialog.svelte
@@ -12,7 +12,7 @@
import { ExternalLinkIcon, SuccessIcon } from '#lib/icons';
import type { AppVersionInformation } from '#lib/types/settings';
import { createQuery, useQueryClient } from '@tanstack/svelte-query';
- import { formatDistanceToNow } from 'date-fns';
+ import { formatRelativeTime } from '#lib/utils/formatting';
import ReleaseNotes from '#lib/components/release-notes.svelte';
import VersionUpdateSummary from './version-update-summary.svelte';
@@ -99,14 +99,7 @@
const releasedAgo = $derived.by(() => {
const at = effectiveReleasedAt;
- if (!at) return '';
- try {
- const date = new Date(at);
- if (Number.isNaN(date.getTime())) return '';
- return formatDistanceToNow(date, { addSuffix: true });
- } catch {
- return '';
- }
+ return at ? formatRelativeTime(at) : '';
});
let upgradeStatus = $state<'upgrading' | 'waiting' | 'ready' | 'complete'>('upgrading');
@@ -224,7 +217,7 @@
// at least 2 unrelated requests successfully. The agent is alive and
// has had time to act on our POST — its response just never came back.
if (triggerResolvedAt === null && successfulPolls >= 2) {
- triggerResolvedAt = Date.now();
+ triggerResolvedAt = performance.now();
log('trigger-implicit-resolved', {
reason: 'agent-answered-poll-without-trigger-response',
successfulPolls
@@ -237,7 +230,7 @@
const changed = versionInfoChanged(baselineVersionInfo, info);
const triggerSettledAt = triggerResolvedAt;
- const sinceTriggerMs = triggerSettledAt === null ? null : Date.now() - triggerSettledAt;
+ const sinceTriggerMs = triggerSettledAt === null ? null : performance.now() - triggerSettledAt;
log('version-check', {
currentVersion: info.currentVersion,
@@ -372,7 +365,7 @@
const triggerPromise = Promise.resolve()
.then(() => onConfirm())
.then((result) => {
- triggerResolvedAt = Date.now();
+ triggerResolvedAt = performance.now();
reportedUpToDate = !!result && result.upToDate === true;
log('trigger-resolved', { upToDate: reportedUpToDate });
})
diff --git a/frontend/src/lib/components/file-browser/FileList.svelte b/frontend/src/lib/components/file-browser/FileList.svelte
index 08627435d..3ad466b42 100644
--- a/frontend/src/lib/components/file-browser/FileList.svelte
+++ b/frontend/src/lib/components/file-browser/FileList.svelte
@@ -19,7 +19,7 @@
import * as Tooltip from '#lib/components/ui/tooltip';
import { openConfirmDialog } from '#lib/components/confirm-dialog';
import RowActionsMenu from './row-actions-menu.svelte';
- import { bytes, formatDateTimeShort } from '#lib/utils/formatting';
+ import { bytes, formatDateTimeShort, instantEpochMilliseconds } from '#lib/utils/formatting';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast';
let {
@@ -60,12 +60,12 @@
// svelte-ignore state_referenced_locally
void mobileFieldVisibility;
- function compareByColumn(a: FileEntry, b: FileEntry, column: string): number {
+ function compareByColumn(a: FileEntry, b: FileEntry, column: string, modTimeMs: Map<FileEntry, number> | null): number {
switch (column) {
case 'size':
return Number(a.size) - Number(b.size);
case 'modTime':
- return new Date(a.modTime).getTime() - new Date(b.modTime).getTime();
+ return (modTimeMs?.get(a) ?? 0) - (modTimeMs?.get(b) ?? 0);
case 'name':
default:
return a.name.localeCompare(b.name);
@@ -76,11 +76,13 @@
const sortColumn = requestOptions?.sort?.column ?? 'name';
const direction = requestOptions?.sort?.direction === 'desc' ? -1 : 1;
const items = files.slice();
+ // Parse once per row instead of per comparison.
+ const modTimeMs = sortColumn === 'modTime' ? new Map(items.map((f) => [f, instantEpochMilliseconds(f.modTime) ?? 0])) : null;
return items.sort((a, b) => {
if (a.isDirectory !== b.isDirectory) {
return a.isDirectory ? -1 : 1;
}
- const diff = compareByColumn(a, b, sortColumn);
+ const diff = compareByColumn(a, b, sortColumn, modTimeMs);
if (diff !== 0) return diff * direction;
return a.name.localeCompare(b.name);
});
diff --git a/frontend/src/lib/components/form/date-picker.svelte b/frontend/src/lib/components/form/date-picker.svelte
index 23f2cebee..3dbf74724 100644
--- a/frontend/src/lib/components/form/date-picker.svelte
+++ b/frontend/src/lib/components/form/date-picker.svelte
@@ -5,59 +5,37 @@
import { m } from '#lib/paraglide/messages';
import { getLocale } from '#lib/paraglide/runtime';
import { cn } from '#lib/utils';
- import { CalendarDate, DateFormatter, getLocalTimeZone, type DateValue } from '@internationalized/date';
+ import { CalendarDate, type DateValue } from '@internationalized/date';
+ import { Temporal } from 'temporal-polyfill';
import type { HTMLAttributes } from 'svelte/elements';
import { CalendarIcon } from '#lib/icons';
type Props = {
- value?: Date;
+ value?: Temporal.PlainDate;
id?: string;
disabled?: boolean;
} & HTMLAttributes<HTMLDivElement>;
let { value = $bindable(undefined), id, disabled = false, ...restProps }: Props = $props();
- let calendarDisplayDate: CalendarDate | undefined = $state(value ? dateToCalendarDate(value) : undefined);
-
let open = $state(false);
- function dateToCalendarDate(d: Date): CalendarDate {
- return new CalendarDate(d.getFullYear(), d.getMonth() + 1, d.getDate());
+ function toCalendarDateInternal(date: Temporal.PlainDate): CalendarDate {
+ return new CalendarDate(date.year, date.month, date.day);
}
- $effect(() => {
- if (calendarDisplayDate) {
- const newExternalDate = calendarDisplayDate.toDate(getLocalTimeZone());
- if (!value || value.getTime() !== newExternalDate.getTime()) {
- value = newExternalDate;
- }
- } else {
- if (value !== undefined) {
- value = undefined;
- }
- }
- });
-
- $effect(() => {
- if (value) {
- const newInternalCalendarDate = dateToCalendarDate(value);
- if (!calendarDisplayDate || calendarDisplayDate.compare(newInternalCalendarDate) !== 0) {
- calendarDisplayDate = newInternalCalendarDate;
- }
- } else {
- if (calendarDisplayDate !== undefined) {
- calendarDisplayDate = undefined;
- }
- }
- });
+ const calendarDisplayDate = $derived(value ? toCalendarDateInternal(value) : undefined);
- function handleCalendarInteraction(_newDateValue?: DateValue) {
+ function handleCalendarInteraction(newDateValue?: DateValue) {
+ value = newDateValue
+ ? Temporal.PlainDate.from({ year: newDateValue.year, month: newDateValue.month, day: newDateValue.day })
+ : undefined;
open = false;
}
- const df = new DateFormatter(getLocale(), {
- dateStyle: 'long'
- });
+ function formatDateInternal(date: Temporal.PlainDate): string {
+ return date.toLocaleString(getLocale(), { dateStyle: 'long' });
+ }
</script>
<div class="w-full" {...restProps}>
@@ -71,13 +49,19 @@
class={cn('w-full justify-start text-left font-normal', !value && 'text-muted-foreground')}
aria-label={m.select_a_date()}
icon={CalendarIcon}
- customLabel={calendarDisplayDate ? df.format(calendarDisplayDate.toDate(getLocalTimeZone())) : m.select_a_date()}
+ customLabel={value ? formatDateInternal(value) : m.select_a_date()}
{disabled}
/>
{/snippet}
</Popover.Trigger>
<Popover.Content class="w-auto p-0" align="start">
- <Calendar type="single" bind:value={calendarDisplayDate} onValueChange={handleCalendarInteraction} initialFocus />
+ <Calendar
+ type="single"
+ value={calendarDisplayDate}
+ onValueChange={handleCalendarInteraction}
+ locale={getLocale()}
+ initialFocus
+ />
</Popover.Content>
</Popover.Root>
</div>
diff --git a/frontend/src/lib/components/form/form-input.svelte b/frontend/src/lib/components/form/form-input.svelte
index a7cb5f9af..c52cea8a0 100644
--- a/frontend/src/lib/components/form/form-input.svelte
+++ b/frontend/src/lib/components/form/form-input.svelte
@@ -5,6 +5,7 @@
import { Textarea } from '#lib/components/ui/textarea';
import { Switch } from '#lib/components/ui/switch';
import { Label } from '#lib/components/ui/label';
+ import type { Temporal } from 'temporal-polyfill';
import type { Snippet } from 'svelte';
import type { HTMLAttributes } from 'svelte/elements';
import type { FormInput } from '#lib/utils/settings';
@@ -23,7 +24,7 @@
autocomplete = 'off',
...restProps
}: HTMLAttributes<HTMLDivElement> & {
- input?: FormInput<string | boolean | number | Date | undefined>;
+ input?: FormInput<string | boolean | number | Temporal.PlainDate | undefined>;
label?: string;
description?: string;
helpText?: string;
@@ -55,7 +56,7 @@
{:else if type === 'textarea'}
<Textarea {id} {placeholder} {rows} bind:value={input.value as string} {disabled} />
{:else if type === 'date'}
- <DatePicker {id} bind:value={input.value as Date} {disabled} />
+ <DatePicker {id} bind:value={input.value as Temporal.PlainDate} {disabled} />
{:else}
<Input {id} {placeholder} {type} bind:value={input.value} {disabled} {autocomplete} />
{/if}
diff --git a/frontend/src/lib/components/form/repo-tag-fields.svelte b/frontend/src/lib/components/form/repo-tag-fields.svelte
index d611df004..8fd0d4ed4 100644
--- a/frontend/src/lib/components/form/repo-tag-fields.svelte
+++ b/frontend/src/lib/components/form/repo-tag-fields.svelte
@@ -4,8 +4,8 @@
import type { FormInput as FormInputType } from '#lib/utils/settings';
interface Props {
- repository: FormInputType<string | boolean | number | Date | undefined>;
- tag: FormInputType<string | boolean | number | Date | undefined>;
+ repository: FormInputType<string | boolean | number | undefined>;
+ tag: FormInputType<string | boolean | number | undefined>;
}
let { repository = $bindable(), tag = $bindable() }: Props = $props();
diff --git a/frontend/src/lib/components/image-update-item.svelte b/frontend/src/lib/components/image-update-item.svelte
index c15296ce0..5dffe1f4a 100644
--- a/frontend/src/lib/components/image-update-item.svelte
+++ b/frontend/src/lib/components/image-update-item.svelte
@@ -24,6 +24,7 @@
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast';
import UncheckedRingIcon from '#lib/components/unchecked-ring-icon.svelte';
import { mergeProps } from 'bits-ui';
+ import { instantEpochMilliseconds, nowInstantString } from '#lib/utils/formatting';
interface Props {
updateInfo?: ImageUpdateData;
@@ -56,8 +57,7 @@
function getCheckTimeValue(info?: ImageUpdateData): number {
if (!info?.checkTime) return 0;
- const parsed = Date.parse(info.checkTime);
- return Number.isNaN(parsed) ? 0 : parsed;
+ return instantEpochMilliseconds(info.checkTime) ?? 0;
}
const imageUpdateQuery = createQuery<ImageUpdateData>(() => ({
@@ -82,7 +82,7 @@
currentDigest: '',
latestVersion: '',
latestDigest: '',
- checkTime: new Date().toISOString(),
+ checkTime: nowInstantString(),
responseTimeMs: 0,
error: imageUpdateQuery.error instanceof Error ? imageUpdateQuery.error.message : m.images_update_check_failed()
};
@@ -190,7 +190,7 @@
currentDigest: '',
latestVersion: '',
latestDigest: '',
- checkTime: new Date().toISOString(),
+ checkTime: nowInstantString(),
responseTimeMs: 0,
error: message
});
@@ -208,7 +208,7 @@
currentDigest: '',
latestVersion: '',
latestDigest: '',
- checkTime: new Date().toISOString(),
+ checkTime: nowInstantString(),
responseTimeMs: 0,
error: (error as Error)?.message || m.images_update_check_failed()
};
diff --git a/frontend/src/lib/components/job-card/job-card.svelte b/frontend/src/lib/components/job-card/job-card.svelte
index ba6d7fe08..34e987872 100644
--- a/frontend/src/lib/components/job-card/job-card.svelte
+++ b/frontend/src/lib/components/job-card/job-card.svelte
@@ -6,8 +6,7 @@
import * as Card from '#lib/components/ui/card';
import { Spinner } from '#lib/components/ui/spinner';
import { jobScheduleService } from '#lib/services/job-schedule-service';
- import { formatDistanceToNow } from 'date-fns';
- import { formatDateTimeShort } from '#lib/utils/formatting';
+ import { formatDateTimeShort, formatRelativeTime, parseInstant } from '#lib/utils/formatting';
import type { Snippet } from 'svelte';
import type { JobStatus } from '#lib/types/settings';
import JobScheduleDialog from './job-schedule-dialog.svelte';
@@ -39,9 +38,10 @@
const nextRunText = $derived.by(() => {
if (!job.nextRun) return null;
- const nextRunDate = new Date(job.nextRun);
- const relative = formatDistanceToNow(nextRunDate, { addSuffix: true });
- const absolute = formatDateTimeShort(nextRunDate);
+ const nextRun = parseInstant(job.nextRun);
+ if (!nextRun) return null;
+ const relative = formatRelativeTime(nextRun);
+ const absolute = formatDateTimeShort(nextRun);
return `${relative} (${absolute})`;
});
diff --git a/frontend/src/lib/components/loading-indicator.svelte b/frontend/src/lib/components/loading-indicator.svelte
index 41998cdbb..3dcc8a7f5 100644
--- a/frontend/src/lib/components/loading-indicator.svelte
+++ b/frontend/src/lib/components/loading-indicator.svelte
@@ -26,10 +26,10 @@
if (active) {
showTO = setTimeout(() => {
visible = true;
- startedAt = Date.now();
+ startedAt = performance.now();
}, delay);
} else {
- const elapsed = Date.now() - startedAt;
+ const elapsed = performance.now() - startedAt;
const remaining = Math.max(0, minDuration - elapsed);
hideTO = setTimeout(() => (visible = false), remaining);
}
diff --git a/frontend/src/lib/components/logs/log-viewer.svelte b/frontend/src/lib/components/logs/log-viewer.svelte
index 59d1757cf..16be1847e 100644
--- a/frontend/src/lib/components/logs/log-viewer.svelte
+++ b/frontend/src/lib/components/logs/log-viewer.svelte
@@ -8,7 +8,7 @@
import { m } from '#lib/paraglide/messages';
import { ReconnectingWebSocket } from '#lib/utils/ws';
import { cn } from '#lib/utils';
- import { ansiToHtml, formatDateTime } from '#lib/utils/formatting';
+ import { ansiToHtml, formatDateTime, nowInstantString } from '#lib/utils/formatting';
import { onDestroy } from 'svelte';
import {
buildLogDisplayEntries,
@@ -284,7 +284,7 @@
function processLogObject(obj: any) {
if (!obj || typeof obj !== 'object') return;
- const { level = 'stdout', message = '', timestamp = new Date().toISOString(), service, containerId } = obj;
+ const { level = 'stdout', message = '', timestamp = nowInstantString(), service, containerId } = obj;
addLogEntry({
level,
@@ -321,7 +321,7 @@
}
function addLogEntry(logData: { level: string; message: string; timestamp?: string; service?: string; containerId?: string }) {
- const timestamp = logData.timestamp || new Date().toISOString();
+ const timestamp = logData.timestamp || nowInstantString();
const { isJson, isStructured, parsed } = tryParseStructuredLog(logData.message);
if (isStructured && !hasAutoEnabledStructuredView && !showParsedJson) {
@@ -452,7 +452,7 @@
if (!timestamp) return '';
return (
formatDateTime(timestamp, {
- datePattern: 'P',
+ dateStyle: 'short',
includeSeconds: true
}) || timestamp
);
diff --git a/frontend/src/lib/components/mobile-nav/gestures.svelte.ts b/frontend/src/lib/components/mobile-nav/gestures.svelte.ts
index ee23431f1..8c101ca46 100644
--- a/frontend/src/lib/components/mobile-nav/gestures.svelte.ts
+++ b/frontend/src/lib/components/mobile-nav/gestures.svelte.ts
@@ -142,7 +142,7 @@ export class MobileNavGestures {
e.preventDefault();
if (this.options.menuOpen || !this.options.scrollToHideEnabled || e.deltaY <= 0) return;
- const now = Date.now();
+ const now = performance.now();
const velocity = e.deltaY / Math.max(1, now - this.lastWheelTime);
if (velocity > this.flickVelocityThreshold) {
diff --git a/frontend/src/lib/components/project-update-item.svelte b/frontend/src/lib/components/project-update-item.svelte
index ed629075d..f009b5736 100644
--- a/frontend/src/lib/components/project-update-item.svelte
+++ b/frontend/src/lib/components/project-update-item.svelte
@@ -53,9 +53,7 @@
const lastCheckedAtLabel = $derived.by(() => {
if (!updateInfo?.lastCheckedAt) return null;
- const parsed = new Date(updateInfo.lastCheckedAt);
- if (Number.isNaN(parsed.getTime())) return null;
- return formatDateTimeShort(parsed);
+ return formatDateTimeShort(updateInfo.lastCheckedAt) || null;
});
const stateMeta = $derived.by(
diff --git a/frontend/src/lib/components/sheets/api-key-form-sheet.svelte b/frontend/src/lib/components/sheets/api-key-form-sheet.svelte
index e7a5fe535..b170fdb15 100644
--- a/frontend/src/lib/components/sheets/api-key-form-sheet.svelte
+++ b/frontend/src/lib/components/sheets/api-key-form-sheet.svelte
@@ -6,6 +6,8 @@
import type { ApiKey } from '#lib/types/auth';
import type { PermissionsManifest, ApiKeyPermissionGrant } from '#lib/types/auth';
import { normalizePermissionSelection } from '#lib/utils/permissions';
+ import { plainDateFromInstant, plainDateToInstantString } from '#lib/utils/formatting';
+ import { Temporal } from 'temporal-polyfill';
import { z } from 'zod/v4';
import { createForm, preventDefault } from '#lib/utils/settings';
import * as m from '#lib/paraglide/messages.js';
@@ -50,7 +52,7 @@
z.object({
name: z.string().min(1, m.common_field_required({ field: m.common_name() })),
description: z.string().optional(),
- expiresAt: z.date().optional(),
+ expiresAt: z.instanceof(Temporal.PlainDate).optional(),
permissions: hidePermissions
? z.array(z.string()).default([])
: z.array(z.string()).min(1, m.pick_at_least_one_permission())
@@ -60,7 +62,7 @@
let formData = $derived({
name: apiKeyToEdit?.name || '',
description: apiKeyToEdit?.description || '',
- expiresAt: apiKeyToEdit?.expiresAt ? new Date(apiKeyToEdit.expiresAt) : undefined,
+ expiresAt: plainDateFromInstant(apiKeyToEdit?.expiresAt),
permissions:
hidePermissions || !manifest
? []
@@ -81,7 +83,7 @@
const apiKeyData = {
name: data.name,
description: data.description || undefined,
- expiresAt: data.expiresAt ? data.expiresAt.toISOString() : undefined,
+ expiresAt: data.expiresAt ? plainDateToInstantString(data.expiresAt) : undefined,
// v1: persist all picks as global grants (environmentId undefined).
// env-scoped picking is a follow-up. Personal keys carry no grants.
...(hidePermissions ? {} : { permissions: data.permissions.map((p) => ({ permission: p })) })
diff --git a/frontend/src/lib/components/sheets/federated-credential-form-sheet.svelte b/frontend/src/lib/components/sheets/federated-credential-form-sheet.svelte
index a8f9a3795..788b7a120 100644
--- a/frontend/src/lib/components/sheets/federated-credential-form-sheet.svelte
+++ b/frontend/src/lib/components/sheets/federated-credential-form-sheet.svelte
@@ -11,8 +11,10 @@
import type { Environment } from '#lib/types/environment';
import { z } from 'zod/v4';
import { createForm, preventDefault } from '#lib/utils/settings';
+ import { plainDateFromInstant, plainDateToInstantString } from '#lib/utils/formatting';
import * as m from '#lib/paraglide/messages.js';
import { InfoIcon } from '#lib/icons';
+ import { Temporal } from 'temporal-polyfill';
type Props = {
open: boolean;
@@ -54,7 +56,7 @@
.int()
.min(60, m.federated_credential_ttl_min())
.max(3600, m.federated_credential_ttl_max()),
- expiresAt: z.date().optional()
+ expiresAt: z.instanceof(Temporal.PlainDate).optional()
});
const formData = $derived({
@@ -69,7 +71,7 @@
roleId: credentialToEdit?.roleId ?? roles[0]?.id ?? '',
environmentId: credentialToEdit?.environmentId ?? GLOBAL_OPTION_ID,
tokenTtlSeconds: credentialToEdit?.tokenTtlSeconds ?? 900,
- expiresAt: credentialToEdit?.expiresAt ? new Date(credentialToEdit.expiresAt) : undefined
+ expiresAt: plainDateFromInstant(credentialToEdit?.expiresAt)
});
const { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
@@ -121,7 +123,7 @@
roleId: data.roleId,
environmentId: data.environmentId === GLOBAL_OPTION_ID ? undefined : data.environmentId,
tokenTtlSeconds: data.tokenTtlSeconds,
- expiresAt: data.expiresAt ? data.expiresAt.toISOString() : undefined
+ expiresAt: data.expiresAt ? plainDateToInstantString(data.expiresAt) : undefined
};
onSubmit({ credential: payload, isEditMode, credentialId: credentialToEdit?.id });
diff --git a/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte b/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte
index 16af404d6..6cd11b55f 100644
--- a/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte
+++ b/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte
@@ -6,7 +6,7 @@
import { onDestroy } from 'svelte';
import type { VulnerabilityScanSummary } from '#lib/types/environment';
import { m } from '#lib/paraglide/messages';
- import { formatTime } from '#lib/utils/formatting';
+ import { formatTime, nowInstantString } from '#lib/utils/formatting';
import { queryKeys } from '#lib/query/query-keys';
import { vulnerabilityService } from '#lib/services/vulnerability-service';
import {
@@ -83,10 +83,7 @@
});
const scanStartedLabel = $derived.by(() => {
const ts = scanSummary?.scanTime ?? lastScanRequestedAt;
- if (!ts) return m.common_na();
- const parsed = new Date(ts);
- if (Number.isNaN(parsed.getTime())) return m.common_na();
- return formatTime(parsed);
+ return ts ? formatTime(ts) || m.common_na() : m.common_na();
});
const statusLabel = $derived.by(() => {
@@ -131,7 +128,7 @@
try {
const result = await scanMutation.mutateAsync();
if (result) {
- lastScanRequestedAt = result.scanTime || new Date().toISOString();
+ lastScanRequestedAt = result.scanTime || nowInstantString();
const summary: VulnerabilityScanSummary = {
imageId: result.imageId,
scanTime: result.scanTime,
diff --git a/frontend/src/lib/hooks/use-swipe-gesture.svelte.ts b/frontend/src/lib/hooks/use-swipe-gesture.svelte.ts
index d22ef3bc1..2860ec43a 100644
--- a/frontend/src/lib/hooks/use-swipe-gesture.svelte.ts
+++ b/frontend/src/lib/hooks/use-swipe-gesture.svelte.ts
@@ -48,7 +48,7 @@ export class SwipeGestureDetector {
this.startX = touch.clientX;
this.startY = touch.clientY;
- this.startTime = Date.now();
+ this.startTime = performance.now();
};
const handleTouchEnd = (e: TouchEvent) => {
@@ -57,7 +57,7 @@ export class SwipeGestureDetector {
const endX = touch.clientX;
const endY = touch.clientY;
- const endTime = Date.now();
+ const endTime = performance.now();
const deltaX = endX - this.startX;
const deltaY = endY - this.startY;
diff --git a/frontend/src/lib/services/auth-service.ts b/frontend/src/lib/services/auth-service.ts
index 2513e35ad..7767c5619 100644
--- a/frontend/src/lib/services/auth-service.ts
+++ b/frontend/src/lib/services/auth-service.ts
@@ -9,6 +9,8 @@ import { activityStore } from '#lib/stores/activity.store.svelte';
import { dashboardStore } from '#lib/stores/dashboard.store.svelte';
import { environmentStatusStore } from '#lib/stores/environment-status.store.svelte';
import { getEffectiveLandingPage } from '#lib/utils/navigation';
+import { parseInstant } from '#lib/utils/formatting';
+import { Temporal } from 'temporal-polyfill';
const REFRESH_TOKEN_KEY = 'arcane_refresh_token';
const TOKEN_EXPIRY_KEY = 'arcane_token_expiry';
@@ -72,9 +74,9 @@ class AuthService extends BaseAPIService {
clearTimeout(this.refreshTimer);
}
- const expiryTime = new Date(expiresAt).getTime();
- const now = Date.now();
- const timeUntilExpiry = expiryTime - now;
+ const expiryTime = parseInstant(expiresAt);
+ if (!expiryTime) return;
+ const timeUntilExpiry = Temporal.Now.instant().until(expiryTime).total('milliseconds');
const refreshTime = Math.max(0, timeUntilExpiry - REFRESH_BUFFER_MS);
if (refreshTime > 0) {
diff --git a/frontend/src/lib/stores/activity.store.svelte.ts b/frontend/src/lib/stores/activity.store.svelte.ts
index eb69b2819..bdc34fc83 100644
--- a/frontend/src/lib/stores/activity.store.svelte.ts
+++ b/frontend/src/lib/stores/activity.store.svelte.ts
@@ -23,6 +23,7 @@ import type { Environment } from '#lib/types/environment';
import userStore from '#lib/stores/user-store';
import { get } from 'svelte/store';
import { discardPendingActivityToasts, queueActivityCompletionToast } from '#lib/components/activity/activity-completion-toasts';
+import { instantEpochMilliseconds } from '#lib/utils/formatting';
const ACTIVITY_LIST_LIMIT = 50;
const ACTIVITY_DETAIL_LIMIT = 500;
@@ -32,11 +33,12 @@ type ActivityEnvironmentState = StreamEnvStateBase & {
};
function sortActivitiesInternal(items: Activity[]): Activity[] {
+ const sortTimeMs = new Map(items.map((a) => [a, getActivitySortTimeInternal(a)]));
return [...items].sort((a, b) => {
const aActive = isActiveStatusInternal(a.status);
const bActive = isActiveStatusInternal(b.status);
if (aActive !== bActive) return aActive ? -1 : 1;
- const diff = getActivitySortTimeInternal(b) - getActivitySortTimeInternal(a);
+ const diff = (sortTimeMs.get(b) ?? 0) - (sortTimeMs.get(a) ?? 0);
if (diff !== 0) return diff;
return b.id.localeCompare(a.id);
});
@@ -46,7 +48,7 @@ function sortActivitiesInternal(items: Activity[]): Activity[] {
// so progress updates never reshuffle them; terminal rows sort by endedAt.
function getActivitySortTimeInternal(activity: Activity): number {
const value = activity.endedAt || activity.createdAt || activity.startedAt;
- return value ? new Date(value).getTime() : 0;
+ return instantEpochMilliseconds(value) ?? 0;
}
function isActiveStatusInternal(status: ActivityStatus): boolean {
diff --git a/frontend/src/lib/utils/docker.ts b/frontend/src/lib/utils/docker.ts
index de944f49b..64433e4d3 100644
--- a/frontend/src/lib/utils/docker.ts
+++ b/frontend/src/lib/utils/docker.ts
@@ -5,6 +5,8 @@ import type { SearchPaginationSortRequest } from '#lib/types/shared';
import type { ProjectUpdateInfo } from '#lib/types/swarm';
import type { SwarmServiceModeName, SwarmServiceModeSpec } from '#lib/types/swarm';
import type { VulnerabilityScanSummary } from '#lib/types/environment';
+import { instantEpochMilliseconds } from '#lib/utils/formatting';
+import type { Temporal } from 'temporal-polyfill';
// --- Compose / Swarm management labels ---
@@ -234,7 +236,7 @@ export type VulnerabilityScanPollOptions = {
};
export type VulnerabilityScanStabilizeOptions = {
- scanRequestedAt?: string | number | Date | null;
+ scanRequestedAt?: string | number | Temporal.Instant | null;
failedRecheckDelayMs?: number;
maxFailedRechecks?: number;
staleFailureGraceMs?: number;
@@ -246,17 +248,12 @@ function delay(ms: number): Promise<void> {
});
}
-function toTimestampMs(value?: string | number | Date | null): number {
+function toTimestampMs(value?: string | number | Temporal.Instant | null): number {
if (value == null) return 0;
- if (value instanceof Date) {
- const ts = value.getTime();
- return Number.isFinite(ts) ? ts : 0;
- }
if (typeof value === 'number') {
return Number.isFinite(value) ? value : 0;
}
- const ts = Date.parse(value);
- return Number.isFinite(ts) ? ts : 0;
+ return instantEpochMilliseconds(value) ?? 0;
}
export function isVulnerabilityScanInProgress(status?: string | null): boolean {
@@ -266,7 +263,7 @@ export function isVulnerabilityScanInProgress(status?: string | null): boolean {
export function isLikelyStaleFailedSummary(
summary: VulnerabilityScanSummary,
- scanRequestedAt?: string | number | Date | null,
+ scanRequestedAt?: string | number | Temporal.Instant | null,
staleFailureGraceMs = 1500
): boolean {
if (summary.status !== 'failed') return false;
diff --git a/frontend/src/lib/utils/formatting.ts b/frontend/src/lib/utils/formatting.ts
index c14f6259b..99ca1d29b 100644
--- a/frontend/src/lib/utils/formatting.ts
+++ b/frontend/src/lib/utils/formatting.ts
@@ -1,7 +1,7 @@
import Convert from 'ansi-to-html';
-import { format as formatDate, setDefaultOptions, type Locale as DateFnsLocale } from 'date-fns';
+import { Temporal } from 'temporal-polyfill';
import { z } from 'zod/v4';
-import { setLocale as setParaglideLocale, type Locale } from '#lib/paraglide/runtime';
+import { getLocale, setLocale as setParaglideLocale, type Locale } from '#lib/paraglide/runtime';
import { timeFormatStore } from '#lib/stores/time-format.store.svelte';
// --- String helpers ---
@@ -160,125 +160,233 @@ export const bytes = bytesWithHelpers;
// --- Locale-aware date/time formatting ---
+export type InstantInput = Temporal.Instant | string | null | undefined;
+
+type DateDisplayStyle = 'short' | 'medium' | 'month-day';
+
type AbsoluteDateTimeFormatOptions = {
- datePattern?: string;
+ dateStyle?: DateDisplayStyle;
includeSeconds?: boolean;
+ timeZone?: string;
};
-function getTimePattern(includeSeconds: boolean): string {
- const timeFormat = timeFormatStore.current;
- if (timeFormat === '12h') {
- return includeSeconds ? 'h:mm:ss a' : 'h:mm a';
+type RelativeTimeFormatOptions = {
+ base?: InstantInput;
+};
+
+type RelativeTimeUnit = 'second' | 'minute' | 'hour' | 'day' | 'month' | 'year';
+
+type RelativeTimeValue = {
+ unit: RelativeTimeUnit;
+ value: number;
+};
+
+const dateTimeFormatterCache = new Map<string, Intl.DateTimeFormat>();
+const relativeTimeFormatterCache = new Map<string, Intl.RelativeTimeFormat>();
+const elapsedTimeFormatterCache = new Map<string, Intl.NumberFormat>();
+
+const dateFormatOptions: Record<DateDisplayStyle, Intl.DateTimeFormatOptions> = {
+ short: { day: 'numeric', month: 'numeric', year: 'numeric' },
+ medium: { day: 'numeric', month: 'short', year: 'numeric' },
+ 'month-day': { day: 'numeric', month: 'short' }
+};
+
+export function parseInstant(value: InstantInput): Temporal.Instant | null {
+ if (!value) return null;
+ if (typeof value !== 'string') return value;
+
+ const normalized = value.trim();
+ // Docker zero-values missing timestamps as 0001-01-01T00:00:00Z.
+ if (!normalized || normalized.startsWith('0001-01-01')) return null;
+
+ try {
+ return Temporal.Instant.from(normalized);
+ } catch {
+ // Third-party-shaped timestamps (offset-less, date-only, human-readable)
+ // that strict ISO parsing rejects but Date historically accepted.
+ const epochMs = Date.parse(normalized);
+ return Number.isNaN(epochMs) ? null : Temporal.Instant.fromEpochMilliseconds(epochMs);
}
- if (timeFormat === '24h') {
- return includeSeconds ? 'HH:mm:ss' : 'HH:mm';
+}
+
+export function instantEpochMilliseconds(value: InstantInput): number | null {
+ return parseInstant(value)?.epochMilliseconds ?? null;
+}
+
+export function nowInstantString(): string {
+ return Temporal.Now.instant().toString({ smallestUnit: 'millisecond' });
+}
+
+// The polyfill's Temporal.Now.timeZoneId() constructs a fresh Intl.DateTimeFormat
+// on every call, so resolve the local zone once per session.
+const localTimeZoneId = Temporal.Now.timeZoneId();
+
+export function plainDateFromInstant(value: InstantInput, timeZone = localTimeZoneId): Temporal.PlainDate | undefined {
+ return parseInstant(value)?.toZonedDateTimeISO(timeZone).toPlainDate();
+}
+
+export function plainDateToInstantString(value: Temporal.PlainDate, timeZone = localTimeZoneId): string {
+ return value.toZonedDateTime({ timeZone, plainTime: '00:00' }).toInstant().toString({ smallestUnit: 'millisecond' });
+}
+
+function dateTimeFormatterInternal(
+ dateStyle: DateDisplayStyle | undefined,
+ includeTime: boolean,
+ includeSeconds: boolean,
+ timeZone: string
+): Intl.DateTimeFormat {
+ const locale = getLocale();
+ const timeFormat = timeFormatStore.current;
+ const key = `${locale}|${timeZone}|${dateStyle ?? 'none'}|${includeTime}|${includeSeconds}|${timeFormat}`;
+ const cached = dateTimeFormatterCache.get(key);
+ if (cached) return cached;
+
+ const options: Intl.DateTimeFormatOptions = {
+ ...(dateStyle ? dateFormatOptions[dateStyle] : {}),
+ timeZone
+ };
+
+ if (includeTime) {
+ options.hour = 'numeric';
+ options.minute = '2-digit';
+ if (includeSeconds) options.second = '2-digit';
+ if (timeFormat === '12h') options.hour12 = true;
+ if (timeFormat === '24h') options.hour12 = false;
}
- return includeSeconds ? 'pp' : 'p';
+
+ const formatter = new Intl.DateTimeFormat(locale, options);
+ dateTimeFormatterCache.set(key, formatter);
+ return formatter;
}
-function formatAbsoluteDateTime(date: Date | string | null | undefined, options: AbsoluteDateTimeFormatOptions): string {
- if (!date) return '';
- const d = typeof date === 'string' ? new Date(date) : date;
- if (isNaN(d.getTime())) return '';
+function formatAbsoluteDateTimeInternal(
+ value: InstantInput,
+ options: AbsoluteDateTimeFormatOptions,
+ includeTime: boolean
+): string {
+ const instant = parseInstant(value);
+ if (!instant) return '';
- const includeSeconds = options.includeSeconds ?? true;
- const timePattern = getTimePattern(includeSeconds);
- const useLocaleLongFormat = timeFormatStore.current === 'auto' && ['P', 'PP'].includes(options.datePattern ?? '');
- const pattern = options.datePattern
- ? useLocaleLongFormat
- ? `${options.datePattern}${timePattern}`
- : `${options.datePattern} ${timePattern}`
- : timePattern;
+ const timeZone = options.timeZone ?? localTimeZoneId;
+ const formatter = dateTimeFormatterInternal(options.dateStyle, includeTime, options.includeSeconds ?? true, timeZone);
+ return formatter.format(instant.epochMilliseconds);
+}
- return formatDate(d, pattern);
+export function formatDate(
+ value: InstantInput,
+ options: Pick<AbsoluteDateTimeFormatOptions, 'dateStyle' | 'timeZone'> = { dateStyle: 'medium' }
+): string {
+ return formatAbsoluteDateTimeInternal(value, { ...options, dateStyle: options.dateStyle ?? 'medium' }, false);
}
export function formatDateTime(
- date: Date | string | null | undefined,
- options: AbsoluteDateTimeFormatOptions = { datePattern: 'PP', includeSeconds: true }
+ value: InstantInput,
+ options: AbsoluteDateTimeFormatOptions = { dateStyle: 'medium', includeSeconds: true }
): string {
- return formatAbsoluteDateTime(date, options);
+ return formatAbsoluteDateTimeInternal(value, { ...options, dateStyle: options.dateStyle ?? 'medium' }, true);
}
-export function formatDateTimeShort(date: Date | string | null | undefined): string {
- return formatAbsoluteDateTime(date, { datePattern: 'PP', includeSeconds: false });
+export function formatDateTimeShort(value: InstantInput): string {
+ return formatAbsoluteDateTimeInternal(value, { dateStyle: 'medium', includeSeconds: false }, true);
}
-export function formatOptionalDateTime(date: Date | string | null | undefined, fallback = '-'): string {
- if (!date) return fallback;
- return formatDateTime(date) || fallback;
+export function formatOptionalDateTime(value: InstantInput, fallback = '-'): string {
+ if (!value) return fallback;
+ return formatDateTime(value) || fallback;
}
-export function isPastDate(date: Date | string | null | undefined): boolean {
- if (!date) return false;
- const d = typeof date === 'string' ? new Date(date) : date;
- return !isNaN(d.getTime()) && d < new Date();
+export function isPastDate(value: InstantInput): boolean {
+ const instant = parseInstant(value);
+ return instant ? Temporal.Instant.compare(instant, Temporal.Now.instant()) < 0 : false;
}
-export function formatTime(date: Date | string | null | undefined): string {
- return formatAbsoluteDateTime(date, { includeSeconds: true });
+export function formatTime(value: InstantInput): string {
+ return formatAbsoluteDateTimeInternal(value, { includeSeconds: true }, true);
}
-type DateFnsLocaleModule = {
- [key: string]: DateFnsLocale;
-};
+function relativeTimeValueInternal(target: Temporal.Instant, base: Temporal.Instant): RelativeTimeValue {
+ const deltaSeconds = (target.epochMilliseconds - base.epochMilliseconds) / 1000;
+ const magnitude = Math.abs(deltaSeconds);
+ const direction = Math.sign(deltaSeconds) || 1;
+ // Math.round rounds halves toward +Infinity, which would make past deltas
+ // round differently than future ones; round the magnitude and reapply the sign.
+ const round = (value: number) => direction * Math.round(magnitude / value);
+
+ // Past sub-30s deltas read as "now"; future ones keep their direction so a
+ // pending run never looks like it already happened.
+ if (magnitude < 30) return { unit: 'second', value: direction > 0 ? Math.max(1, Math.round(magnitude)) : 0 };
+ if (magnitude < 90) return { unit: 'minute', value: direction };
+ if (magnitude < 45 * 60) return { unit: 'minute', value: round(60) };
+ if (magnitude < 90 * 60) return { unit: 'hour', value: direction };
+ if (magnitude < 22 * 60 * 60) return { unit: 'hour', value: round(60 * 60) };
+ if (magnitude < 36 * 60 * 60) return { unit: 'day', value: direction };
+ if (magnitude < 26 * 24 * 60 * 60) return { unit: 'day', value: round(24 * 60 * 60) };
+ if (magnitude < 45 * 24 * 60 * 60) return { unit: 'month', value: direction };
+ if (magnitude < 320 * 24 * 60 * 60) {
+ return { unit: 'month', value: round(30.4375 * 24 * 60 * 60) };
+ }
+ if (magnitude < 548 * 24 * 60 * 60) return { unit: 'year', value: direction };
+ return { unit: 'year', value: round(365.2425 * 24 * 60 * 60) };
+}
-function resolveDateFnsLocale(loader: () => Promise<DateFnsLocaleModule>): Promise<DateFnsLocale> {
- return loader().then((module) => {
- const locale = (module as { default?: DateFnsLocale }).default ?? Object.values(module)[0];
- if (!locale) {
- throw new Error('date-fns locale module did not export a locale');
- }
- return locale;
+function relativeTimeFormatterInternal(numeric: 'always' | 'auto'): Intl.RelativeTimeFormat {
+ const locale = getLocale();
+ const key = `${locale}|${numeric}`;
+ const cached = relativeTimeFormatterCache.get(key);
+ if (cached) return cached;
+
+ const formatter = new Intl.RelativeTimeFormat(locale, { numeric });
+ relativeTimeFormatterCache.set(key, formatter);
+ return formatter;
+}
+
+export function formatRelativeTime(value: InstantInput, options: RelativeTimeFormatOptions = {}): string {
+ const target = parseInstant(value);
+ const base = options.base ? parseInstant(options.base) : Temporal.Now.instant();
+ if (!target || !base) return '';
+
+ const relative = relativeTimeValueInternal(target, base);
+ const numeric = relative.value === 0 ? 'auto' : 'always';
+ return relativeTimeFormatterInternal(numeric).format(relative.value, relative.unit);
+}
+
+function elapsedTimeFormatterInternal(unit: RelativeTimeUnit): Intl.NumberFormat {
+ const locale = getLocale();
+ const key = `${locale}|${unit}`;
+ const cached = elapsedTimeFormatterCache.get(key);
+ if (cached) return cached;
+
+ const formatter = new Intl.NumberFormat(locale, {
+ style: 'unit',
+ unit,
+ unitDisplay: 'long'
});
+ elapsedTimeFormatterCache.set(key, formatter);
+ return formatter;
}
-const dateFnsLocaleLoaders: Record<Locale, () => Promise<DateFnsLocale>> = {
- cs: () => resolveDateFnsLocale(() => import('date-fns/locale/cs')),
- da: () => resolveDateFnsLocale(() => import('date-fns/locale/da')),
- de: () => resolveDateFnsLocale(() => import('date-fns/locale/de')),
- el: () => resolveDateFnsLocale(() => import('date-fns/locale/el')),
- en: () => resolveDateFnsLocale(() => import('date-fns/locale/en-US')),
- eo: () => resolveDateFnsLocale(() => import('date-fns/locale/eo')),
- es: () => resolveDateFnsLocale(() => import('date-fns/locale/es')),
- fr: () => resolveDateFnsLocale(() => import('date-fns/locale/fr')),
- hu: () => resolveDateFnsLocale(() => import('date-fns/locale/hu')),
- it: () => resolveDateFnsLocale(() => import('date-fns/locale/it')),
- ja: () => resolveDateFnsLocale(() => import('date-fns/locale/ja')),
- ko: () => resolveDateFnsLocale(() => import('date-fns/locale/ko')),
- nl: () => resolveDateFnsLocale(() => import('date-fns/locale/nl')),
- pl: () => resolveDateFnsLocale(() => import('date-fns/locale/pl')),
- 'pt-BR': () => resolveDateFnsLocale(() => import('date-fns/locale/pt-BR')),
- ru: () => resolveDateFnsLocale(() => import('date-fns/locale/ru')),
- sv: () => resolveDateFnsLocale(() => import('date-fns/locale/sv')),
- tr: () => resolveDateFnsLocale(() => import('date-fns/locale/tr')),
- uk: () => resolveDateFnsLocale(() => import('date-fns/locale/uk')),
- vi: () => resolveDateFnsLocale(() => import('date-fns/locale/vi')),
- 'zh-CN': () => resolveDateFnsLocale(() => import('date-fns/locale/zh-CN')),
- 'zh-TW': () => resolveDateFnsLocale(() => import('date-fns/locale/zh-TW'))
-};
+export function formatElapsedTime(value: InstantInput, options: RelativeTimeFormatOptions = {}): string {
+ const target = parseInstant(value);
+ const base = options.base ? parseInstant(options.base) : Temporal.Now.instant();
+ if (!target || !base) return '';
+
+ const relative = relativeTimeValueInternal(target, base);
+ const elapsedValue =
+ relative.value === 0
+ ? Math.round(Math.abs(target.epochMilliseconds - base.epochMilliseconds) / 1000)
+ : Math.abs(relative.value);
+ return elapsedTimeFormatterInternal(relative.unit).format(elapsedValue);
+}
export async function setLocale(locale: Locale, reload = true) {
- const [zodResult, dateFnsResult] = await Promise.allSettled([
- import(`../../../node_modules/zod/v4/locales/${locale}.js`),
- dateFnsLocaleLoaders[locale]()
- ]);
-
- if (zodResult.status === 'fulfilled') {
- z.config(zodResult.value.default());
- } else {
- console.warn(`Failed to load zod locale for ${locale}:`, zodResult.reason);
+ try {
+ const zodLocale = await import(`../../../node_modules/zod/v4/locales/${locale}.js`);
+ z.config(zodLocale.default());
+ } catch (error) {
+ console.warn(`Failed to load zod locale for ${locale}:`, error);
}
setParaglideLocale(locale, { reload });
-
- if (dateFnsResult.status === 'fulfilled') {
- setDefaultOptions({
- locale: dateFnsResult.value
- });
- } else {
- console.warn(`Failed to load date-fns locale for ${locale}:`, dateFnsResult.reason);
- }
}
// --- ANSI conversion ---
diff --git a/frontend/src/lib/utils/image-updates.ts b/frontend/src/lib/utils/image-updates.ts
index c46841ae3..ce67ed284 100644
--- a/frontend/src/lib/utils/image-updates.ts
+++ b/frontend/src/lib/utils/image-updates.ts
@@ -15,7 +15,5 @@ export function formatImageUpdateValue(updateInfo: ImageUpdateInfoDto | undefine
export function formatImageUpdateCheckedAt(value: string) {
if (!value) return '-';
- const parsed = new Date(value);
- if (Number.isNaN(parsed.getTime())) return '-';
- return formatDateTimeShort(parsed);
+ return formatDateTimeShort(value) || '-';
}
diff --git a/frontend/src/lib/utils/streaming.ts b/frontend/src/lib/utils/streaming.ts
index 7c8b921db..a63f5ccd5 100644
--- a/frontend/src/lib/utils/streaming.ts
+++ b/frontend/src/lib/utils/streaming.ts
@@ -1,3 +1,5 @@
+import { Temporal } from 'temporal-polyfill';
+
/**
* Returns a value unique to each call, for use as a cache-busting query param on
* stream URLs. Without it, intermediaries that key on the URL — a reverse proxy
@@ -12,7 +14,7 @@ export function streamCacheBuster(): string {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return crypto.randomUUID();
}
- return `${Date.now()}-${Math.random().toString(36).slice(2)}`;
+ return `${Temporal.Now.instant().epochMilliseconds}-${Math.random().toString(36).slice(2)}`;
}
/**
diff --git a/frontend/src/lib/utils/swarm-kv.ts b/frontend/src/lib/utils/swarm-kv.ts
index 740a1541e..8006ced07 100644
--- a/frontend/src/lib/utils/swarm-kv.ts
+++ b/frontend/src/lib/utils/swarm-kv.ts
@@ -1,5 +1,5 @@
import { m } from '#lib/paraglide/messages';
-import { formatDistanceToNow } from 'date-fns';
+import { formatRelativeTime } from '#lib/utils/formatting';
export function getSwarmSpecName(spec: Record<string, unknown> | null | undefined, fallback: string): string {
const name = spec && typeof spec === 'object' ? spec['Name'] : undefined;
@@ -27,5 +27,5 @@ export function encodeTextToBase64(value: string): string {
export function formatSwarmTimestamp(timestamp: string): string {
if (!timestamp) return m.common_unknown();
- return formatDistanceToNow(new Date(timestamp), { addSuffix: true });
+ return formatRelativeTime(timestamp) || m.common_unknown();
}
diff --git a/frontend/src/lib/utils/swarm-tasks.ts b/frontend/src/lib/utils/swarm-tasks.ts
index 17591edde..c0b43cbb6 100644
--- a/frontend/src/lib/utils/swarm-tasks.ts
+++ b/frontend/src/lib/utils/swarm-tasks.ts
@@ -1,4 +1,5 @@
import type { SwarmTaskSummary } from '#lib/types/swarm';
+import { instantEpochMilliseconds } from '#lib/utils/formatting';
const SWARM_TASK_STATE_ORDER: Record<string, number> = {
running: 0,
@@ -28,10 +29,11 @@ export function getSwarmTaskIconVariant(state: string): 'emerald' | 'amber' | 'r
}
export function sortSwarmTasks(raw: SwarmTaskSummary[]): SwarmTaskSummary[] {
+ const updatedMs = new Map(raw.map((t) => [t, instantEpochMilliseconds(t.updatedAt) ?? 0]));
return [...raw].sort((a, b) => {
const stateA = SWARM_TASK_STATE_ORDER[a.currentState] ?? 99;
const stateB = SWARM_TASK_STATE_ORDER[b.currentState] ?? 99;
if (stateA !== stateB) return stateA - stateB;
- return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();
+ return (updatedMs.get(b) ?? 0) - (updatedMs.get(a) ?? 0);
});
}
diff --git a/frontend/src/routes/(app)/account/+page.svelte b/frontend/src/routes/(app)/account/+page.svelte
index 198084b14..066104735 100644
--- a/frontend/src/routes/(app)/account/+page.svelte
+++ b/frontend/src/routes/(app)/account/+page.svelte
@@ -4,7 +4,6 @@
import { toast } from 'svelte-sonner';
import { mode } from 'mode-watcher';
import ThemeModeSelector from '#lib/components/theme-mode/theme-mode-selector.svelte';
- import { format, formatDistanceToNow } from 'date-fns';
import HeaderCard from '#lib/components/header-card.svelte';
import ApiKeyFormSheet from '#lib/components/sheets/api-key-form-sheet.svelte';
import PasskeySettings from '#lib/components/auth/passkey-settings.svelte';
@@ -34,10 +33,12 @@
import settingsStore from '#lib/stores/config-store';
import { getDefaultProfilePicture } from '#lib/utils/docker';
import { avatarUploadLimitBytes, prepareAvatarUploadFile } from '#lib/utils/avatar-upload';
+ import { formatDate, formatRelativeTime } from '#lib/utils/formatting';
import { cn } from '#lib/utils';
import { GLOBAL_SCOPE } from '#lib/types/auth';
import type { ApiKey, ApiKeyCreated, ApiKeyPermissionGrant, CreateUserApiKey, UserPreferences } from '#lib/types/auth';
import type { ApplicationTheme, IconCatalog } from '#lib/types/settings';
+ import { Temporal } from 'temporal-polyfill';
import {
UserIcon,
LogoutIcon,
@@ -79,24 +80,6 @@
return BUILT_IN_ROLE_LABELS[roleId] ?? roleId.replace(/^role_/, '').replace(/_/g, ' ');
}
- function safeFormatDate(input: string | undefined, fmt: string): string | null {
- if (!input) return null;
- try {
- return format(new Date(input), fmt);
- } catch {
- return null;
- }
- }
-
- function safeFormatRelative(input: string | undefined): string | null {
- if (!input) return null;
- try {
- return formatDistanceToNow(new Date(input), { addSuffix: true });
- } catch {
- return null;
- }
- }
-
const currentUser = $derived($userStore);
const isOidcUser = $derived(Boolean(currentUser?.oidcSubjectId));
@@ -121,7 +104,7 @@
let revokingAll = $state(false);
let avatarUrl = $state<string>(getDefaultProfilePicture());
- let avatarCacheBuster = $state(Date.now());
+ let avatarCacheBuster = $state(Temporal.Now.instant().epochMilliseconds);
const avatarSrc = $derived(currentUser?.avatarUrl ? `${currentUser.avatarUrl}?t=${avatarCacheBuster}` : '');
let cropperAvatarSrc = $derived(avatarSrc || avatarUrl);
@@ -279,7 +262,7 @@
const updatedUser = await userService.uploadMyAvatar(preparedFile.file);
await userStore.setUser(updatedUser);
- avatarCacheBuster = Date.now();
+ avatarCacheBuster = Temporal.Now.instant().epochMilliseconds;
toast.success(m.account_avatar_upload_success());
} catch (err) {
toast.error(err instanceof Error ? err.message : m.account_avatar_upload_failed());
@@ -304,7 +287,7 @@
try {
const updatedUser = await userService.deleteMyAvatar();
await userStore.setUser(updatedUser);
- avatarCacheBuster = Date.now();
+ avatarCacheBuster = Temporal.Now.instant().epochMilliseconds;
toast.success(m.account_avatar_remove_success());
} catch (err) {
toast.error(err instanceof Error ? err.message : m.account_avatar_remove_failed());
@@ -501,15 +484,15 @@
</div>
</div>
<div class="hidden text-right sm:block">
- {#if safeFormatDate(currentUser.createdAt, 'PP')}
+ {#if formatDate(currentUser.createdAt)}
<div class="text-xs text-muted-foreground">
{m.account_member_since()}
- {safeFormatDate(currentUser.createdAt, 'PP')}
+ {formatDate(currentUser.createdAt)}
</div>
{/if}
<div class="text-xs text-muted-foreground" title={currentUser.lastLogin ?? ''}>
{m.account_last_login_prefix()}
- {safeFormatRelative(currentUser.lastLogin) ?? m.common_never()}
+ {formatRelativeTime(currentUser.lastLogin) || m.common_never()}
</div>
</div>
</div>
@@ -709,11 +692,11 @@
</div>
<div class="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
<code class="rounded bg-muted/40 px-1.5 py-0.5 font-mono">{key.keyPrefix}…</code>
- {#if safeFormatDate(key.createdAt, 'PP')}
- <span>{m.common_created()} {safeFormatDate(key.createdAt, 'PP')}</span>
+ {#if formatDate(key.createdAt)}
+ <span>{m.common_created()} {formatDate(key.createdAt)}</span>
<span aria-hidden="true">·</span>
{/if}
- <span>{m.last_used()} {safeFormatRelative(key.lastUsedAt) ?? m.common_never()}</span>
+ <span>{m.last_used()} {formatRelativeTime(key.lastUsedAt) || m.common_never()}</span>
</div>
</li>
{/each}
diff --git a/frontend/src/routes/(app)/containers/components/ContainerHealthcheck.svelte b/frontend/src/routes/(app)/containers/components/ContainerHealthcheck.svelte
index 47814ae93..5e8b7eeaa 100644
--- a/frontend/src/routes/(app)/containers/components/ContainerHealthcheck.svelte
+++ b/frontend/src/routes/(app)/containers/components/ContainerHealthcheck.svelte
@@ -4,8 +4,8 @@
import { m } from '#lib/paraglide/messages';
import type { ContainerDetailsDto, ContainerHealthLogEntry, ContainerHealthcheckDto } from '#lib/types/docker';
import { HealthIcon, SettingsIcon, FileTextIcon } from '#lib/icons';
- import { formatDistanceToNow } from 'date-fns';
- import { formatDateTime } from '#lib/utils/formatting';
+ import { formatDateTime, formatRelativeTime, parseInstant } from '#lib/utils/formatting';
+ import { Temporal } from 'temporal-polyfill';
interface Props {
container: ContainerDetailsDto;
@@ -19,7 +19,7 @@
// Docker sends duration values in nanoseconds. Convert to a compact human string.
function formatDurationNs(ns: number | undefined | null): string {
if (!ns || ns <= 0) return m.common_unknown();
- const ms = ns / 1_000_000;
+ const ms = Temporal.Duration.from({ nanoseconds: Math.trunc(ns) }).total('milliseconds');
if (ms < 1000) return `${Math.round(ms)}ms`;
const totalSeconds = Math.round(ms / 1000);
if (totalSeconds < 60) return `${totalSeconds}s`;
@@ -31,20 +31,12 @@
return mins ? `${hours}h ${mins}m` : `${hours}h`;
}
- function parseDockerDate(input: string | undefined | null): Date | null {
- if (!input) return null;
- const s = String(input).trim();
- if (!s || s.startsWith('0001-01-01')) return null;
- const d = new Date(s);
- return isNaN(d.getTime()) ? null : d;
- }
-
function normalizeLog(entries: ContainerHealthLogEntry[] | undefined) {
if (!entries) return [];
return entries
.map((e) => ({
- start: parseDockerDate(e.start),
- end: parseDockerDate(e.end),
+ start: parseInstant(e.start),
+ end: parseInstant(e.end),
exitCode: (e.exitCode ?? 0) as number,
output: (e.output ?? '') as string
}))
@@ -78,26 +70,25 @@
});
// Estimate the next probe time: lastProbe.end + interval (clamped to "now" if overdue).
- const nextCheck = $derived.by<{ at: Date; overdue: boolean } | null>(() => {
+ const nextCheck = $derived.by<{ at: Temporal.Instant; overdue: boolean } | null>(() => {
if (!container?.state?.running) return null;
const intervalNs = healthcheck?.interval;
if (!intervalNs || !lastProbe?.end) return null;
- const next = new Date(lastProbe.end.getTime() + intervalNs / 1_000_000);
- const now = new Date();
- return { at: next, overdue: next.getTime() <= now.getTime() };
+ const next = lastProbe.end.add({ nanoseconds: Math.trunc(intervalNs) });
+ return { at: next, overdue: Temporal.Instant.compare(next, Temporal.Now.instant()) <= 0 };
});
- function probeDuration(start: Date | null, end: Date | null): string {
+ function probeDuration(start: Temporal.Instant | null, end: Temporal.Instant | null): string {
if (!start || !end) return '—';
- const ms = end.getTime() - start.getTime();
+ const ms = start.until(end, { largestUnit: 'millisecond' }).total('milliseconds');
if (ms < 0) return '—';
- if (ms < 1000) return `${ms}ms`;
+ if (ms < 1000) return `${Math.round(ms)}ms`;
return `${(ms / 1000).toFixed(2)}s`;
}
- function formatProbeDate(d: Date | null): string {
- if (!d) return '—';
- return formatDateTime(d) || d.toISOString();
+ function formatProbeDate(instant: Temporal.Instant | null): string {
+ if (!instant) return '—';
+ return formatDateTime(instant) || instant.toString({ smallestUnit: 'millisecond' });
}
const retriesBudget = $derived.by(() => {
@@ -107,8 +98,8 @@
return { retries, failing, remaining: Math.max(0, retries - failing) };
});
- function probeKey(probe: { start: Date | null; end: Date | null; exitCode: number }): string {
- return `${probe.start?.getTime() ?? ''}-${probe.end?.getTime() ?? ''}-${probe.exitCode}`;
+ function probeKey(probe: { start: Temporal.Instant | null; end: Temporal.Instant | null; exitCode: number }): string {
+ return `${probe.start?.epochNanoseconds ?? ''}-${probe.end?.epochNanoseconds ?? ''}-${probe.exitCode}`;
}
let expanded = $state<Record<string, boolean>>({});
@@ -174,7 +165,7 @@
{#if nextCheck.overdue}
{m.health_next_check_running_now()}
{:else}
- {formatDistanceToNow(nextCheck.at, { addSuffix: true })}
+ {formatRelativeTime(nextCheck.at)}
{/if}
</div>
</Card.Content>
@@ -298,7 +289,7 @@
>{`${m.health_exit_code()}: ${probe.exitCode}`}</Badge
>
<span class="text-xs text-muted-foreground" title={formatProbeDate(probe.start)}>
- {probe.start ? formatDistanceToNow(probe.start, { addSuffix: true }) : '—'}
+ {probe.start ? formatRelativeTime(probe.start) : '—'}
</span>
<span class="text-xs text-muted-foreground">
{m.duration()}: {probeDuration(probe.start, probe.end)}
diff --git a/frontend/src/routes/(app)/containers/components/ContainerOverview.svelte b/frontend/src/routes/(app)/containers/components/ContainerOverview.svelte
index de6c0de53..d091fee60 100644
--- a/frontend/src/routes/(app)/containers/components/ContainerOverview.svelte
+++ b/frontend/src/routes/(app)/containers/components/ContainerOverview.svelte
@@ -3,8 +3,7 @@
import { Switch } from '#lib/components/ui/switch';
import { m } from '#lib/paraglide/messages';
import type { ContainerDetailsDto } from '#lib/types/docker';
- import { formatDistanceToNow } from 'date-fns';
- import { formatDateTimeShort } from '#lib/utils/formatting';
+ import { formatDateTimeShort, formatElapsedTime, formatRelativeTime, parseInstant } from '#lib/utils/formatting';
import { StartIcon, StopIcon, NetworksIcon, VolumesIcon, HealthIcon } from '#lib/icons';
import { containerService } from '#lib/services/container-service';
import { DetailMetaStrip, DetailSection, KeyValueCard, type DetailMetaItem } from '#lib/components/resource-detail';
@@ -43,50 +42,9 @@
}
}
- function parseDockerDate(input: string | Date | undefined | null): Date | null {
- if (!input) return null;
- if (input instanceof Date) return isNaN(input.getTime()) ? null : input;
-
- const s = String(input).trim();
- if (!s || s.startsWith('0001-01-01')) return null;
-
- const m = s.match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(\.\d+)?Z$/);
- let normalized = s;
- if (m) {
- const base = m[1];
- const frac = m[2] ? m[2].slice(1) : '';
- const ms = frac ? '.' + frac.slice(0, 3).padEnd(3, '0') : '';
- normalized = `${base}${ms}Z`;
- }
-
- const d = new Date(normalized);
- return isNaN(d.getTime()) ? null : d;
- }
-
- function formatDockerDate(input: string | Date | undefined | null): string {
- const d = parseDockerDate(input);
- return d ? formatDateTimeShort(d) : 'N/A';
- }
-
- function formatRelativeDate(input: string | Date | undefined | null): string {
- const d = parseDockerDate(input);
- if (!d) return 'N/A';
- try {
- return formatDistanceToNow(d, { addSuffix: true });
- } catch {
- return 'N/A';
- }
- }
-
- function getUptime(input: string | Date | undefined | null): string {
- const d = parseDockerDate(input);
- if (!d) return 'N/A';
- try {
- return formatDistanceToNow(d, { addSuffix: false });
- } catch {
- return 'N/A';
- }
- }
+ const createdInstant = $derived(parseInstant(container.created));
+ const startedInstant = $derived(parseInstant(container.state?.startedAt));
+ const finishedInstant = $derived(parseInstant(container.state?.finishedAt));
const restartPolicy = $derived(container.hostConfig?.restartPolicy || 'no');
@@ -124,7 +82,7 @@
const metaItems = $derived.by(() => {
const items: DetailMetaItem[] = [{ icon: VolumesIcon, value: container.image || m.common_na(), mono: true }];
if (container.state?.running) {
- items.push({ icon: StartIcon, label: m.common_uptime(), value: getUptime(container.state.startedAt) });
+ items.push({ icon: StartIcon, label: m.common_uptime(), value: formatElapsedTime(startedInstant) || m.common_na() });
} else {
items.push({ icon: StopIcon, value: container.state?.status || m.common_stopped() });
}
@@ -166,19 +124,19 @@
<KeyValueCard label={m.common_image_id()} valueTitle={m.common_click_to_select()}>{container.imageId}</KeyValueCard>
<KeyValueCard label={m.common_created()} valueClass="text-sm font-medium text-foreground">
- {formatRelativeDate(container?.created)}
- <div class="text-xs font-normal text-muted-foreground">{formatDockerDate(container?.created)}</div>
+ {formatRelativeTime(createdInstant) || m.common_na()}
+ <div class="text-xs font-normal text-muted-foreground">{formatDateTimeShort(createdInstant) || m.common_na()}</div>
</KeyValueCard>
{#if container.state?.running}
<KeyValueCard label={m.common_started()} valueClass="text-sm font-medium text-foreground">
- {formatRelativeDate(container.state.startedAt)}
- <div class="text-xs font-normal text-muted-foreground">{formatDockerDate(container.state.startedAt)}</div>
+ {formatRelativeTime(startedInstant) || m.common_na()}
+ <div class="text-xs font-normal text-muted-foreground">{formatDateTimeShort(startedInstant) || m.common_na()}</div>
</KeyValueCard>
{:else if container.state?.finishedAt && !container.state.finishedAt.startsWith('0001')}
<KeyValueCard label={m.common_finished()} valueClass="text-sm font-medium text-foreground">
- {formatRelativeDate(container.state.finishedAt)}
- <div class="text-xs font-normal text-muted-foreground">{formatDockerDate(container.state.finishedAt)}</div>
+ {formatRelativeTime(finishedInstant) || m.common_na()}
+ <div class="text-xs font-normal text-muted-foreground">{formatDateTimeShort(finishedInstant) || m.common_na()}</div>
</KeyValueCard>
{/if}
diff --git a/frontend/src/routes/(app)/containers/container-table.svelte b/frontend/src/routes/(app)/containers/container-table.svelte
index 14143b593..708fdb4f7 100644
--- a/frontend/src/routes/(app)/containers/container-table.svelte
+++ b/frontend/src/routes/(app)/containers/container-table.svelte
@@ -32,6 +32,7 @@
import IconImage from '#lib/components/icon-image.svelte';
import { COMPOSE_PROJECT_LABEL, getContainerIpAddresses, getThemedIconUrl, parseImageRef } from '#lib/utils/docker';
import { hasAnyLoadingState } from '#lib/utils/bulk-actions';
+ import { Temporal } from 'temporal-polyfill';
import { createContainerActions } from './container-table.actions';
import {
getActionStatusMessage,
@@ -500,7 +501,7 @@
{#snippet CreatedCell({ item }: { item: ContainerSummaryDto })}
<span class="text-sm">
- {item.created ? formatDateTimeShort(new Date(item.created * 1000)) : m.common_na()}
+ {item.created ? formatDateTimeShort(Temporal.Instant.fromEpochMilliseconds(item.created * 1000)) : m.common_na()}
</span>
{/snippet}
@@ -586,7 +587,7 @@
footer={(mobileFieldVisibility['created'] ?? true)
? {
label: m.common_created(),
- getValue: (item) => formatDateTimeShort(new Date(item.created * 1000)),
+ getValue: (item) => formatDateTimeShort(Temporal.Instant.fromEpochMilliseconds(item.created * 1000)),
icon: ClockIcon
}
: undefined}
diff --git a/frontend/src/routes/(app)/customize/variables/variable-table.svelte b/frontend/src/routes/(app)/customize/variables/variable-table.svelte
index 1a08fab0d..13d4f9458 100644
--- a/frontend/src/routes/(app)/customize/variables/variable-table.svelte
+++ b/frontend/src/routes/(app)/customize/variables/variable-table.svelte
@@ -13,7 +13,7 @@
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared';
import { VariableIcon, LockIcon, EditIcon, TrashIcon, ClockIcon, GlobeIcon } from '#lib/icons';
import { m } from '#lib/paraglide/messages';
- import { formatDateTime } from '#lib/utils/formatting';
+ import { formatDateTime, instantEpochMilliseconds } from '#lib/utils/formatting';
let {
variables = $bindable(),
@@ -59,7 +59,8 @@
list.sort((a, b) => a.key.localeCompare(b.key));
if (sort.direction === 'desc') list.reverse();
} else if (sort?.column === 'updatedAt') {
- list.sort((a, b) => new Date(updatedTimestamp(a)).getTime() - new Date(updatedTimestamp(b)).getTime());
+ const updatedMs = new Map(list.map((v) => [v, instantEpochMilliseconds(updatedTimestamp(v)) ?? 0]));
+ list.sort((a, b) => (updatedMs.get(a) ?? 0) - (updatedMs.get(b) ?? 0));
if (sort.direction === 'desc') list.reverse();
}
return list;
diff --git a/frontend/src/routes/(app)/dashboard/+page.svelte b/frontend/src/routes/(app)/dashboard/+page.svelte
index cd767e1a8..2419ea4d8 100644
--- a/frontend/src/routes/(app)/dashboard/+page.svelte
+++ b/frontend/src/routes/(app)/dashboard/+page.svelte
@@ -4,6 +4,7 @@
import DashboardAllEnvironmentsView from './dashboard-all-environments-view.svelte';
import userStore from '#lib/stores/user-store';
import { m } from '#lib/paraglide/messages';
+ import { Temporal } from 'temporal-polyfill';
let { data }: PageProps = $props();
@@ -24,7 +25,7 @@
});
const greetingBase = $derived.by(() => {
- const hour = new Date().getHours();
+ const hour = Temporal.Now.zonedDateTimeISO().hour;
if (hour >= 5 && hour < 12) return m.dashboard_greeting_morning();
if (hour >= 12 && hour < 18) return m.dashboard_greeting_afternoon();
if (hour >= 18 && hour < 23) return m.dashboard_greeting_evening();
diff --git a/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte b/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte
index d7a3bada4..ac4f370a2 100644
--- a/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte
+++ b/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte
@@ -1,6 +1,5 @@
<script lang="ts">
import { goto, refreshAll } from '$app/navigation';
- import { formatDistanceToNow } from 'date-fns';
import { onDestroy, onMount, untrack } from 'svelte';
import { toast } from 'svelte-sonner';
import { type ActionButton } from '#lib/components/action-button-group/index.js';
@@ -19,7 +18,7 @@
import { environmentStore, LOCAL_DOCKER_ENVIRONMENT_ID } from '#lib/stores/environment.store.svelte';
import userStore from '#lib/stores/user-store';
import { hasAnyPermission, hasPermission } from '#lib/utils/auth';
- import { formatDateTime } from '#lib/utils/formatting';
+ import { formatDateTime, formatRelativeTime, parseInstant } from '#lib/utils/formatting';
import type {
DashboardActionItemKind,
DashboardEnvironmentCardState,
@@ -480,14 +479,14 @@
return { label: m.activity(), value: m.common_never(), title: m.common_never() };
}
- const parsed = new Date(labelAndValue.raw);
- if (Number.isNaN(parsed.getTime())) {
+ const parsed = parseInstant(labelAndValue.raw);
+ if (!parsed) {
return { label: labelAndValue.label, value: m.common_unknown(), title: m.common_unknown() };
}
return {
label: labelAndValue.label,
- value: formatDistanceToNow(parsed, { addSuffix: true }),
+ value: formatRelativeTime(parsed),
title: formatDateTime(parsed)
};
}
diff --git a/frontend/src/routes/(app)/environments/[id]/components/ConnectionEdgeTab.svelte b/frontend/src/routes/(app)/environments/[id]/components/ConnectionEdgeTab.svelte
index 536b9a290..7158b0e95 100644
--- a/frontend/src/routes/(app)/environments/[id]/components/ConnectionEdgeTab.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/components/ConnectionEdgeTab.svelte
@@ -26,17 +26,6 @@
}
return { text: m.environments_edge_mtls_certificate_status_valid(), variant: 'green' };
});
-
- function formatDateTime(value?: string): string {
- if (!value) return m.common_never();
-
- const date = new Date(value);
- if (Number.isNaN(date.getTime())) {
- return m.common_unknown();
- }
-
- return formatDateTimeShort(date);
- }
</script>
{#snippet badgeTile(label: string, text: string, variant: BadgeVariant)}
@@ -93,7 +82,9 @@
)}
{@render tile(
m.environments_edge_mtls_certificate_expires_label(),
- environment.edgeMTLSCertificate.expiresAt ? formatDateTime(environment.edgeMTLSCertificate.expiresAt) : '—',
+ environment.edgeMTLSCertificate.expiresAt
+ ? formatDateTimeShort(environment.edgeMTLSCertificate.expiresAt) || m.common_unknown()
+ : '—',
{
subtext:
environment.edgeMTLSCertificate.daysRemaining !== undefined
diff --git a/frontend/src/routes/(app)/environments/[id]/components/EnvironmentConnectionDetails.svelte b/frontend/src/routes/(app)/environments/[id]/components/EnvironmentConnectionDetails.svelte
index e12ea3611..a5726f789 100644
--- a/frontend/src/routes/(app)/environments/[id]/components/EnvironmentConnectionDetails.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/components/EnvironmentConnectionDetails.svelte
@@ -57,17 +57,6 @@
return { text: m.inactive(), variant: 'gray' };
});
-
- function formatDateTime(value?: string): string {
- if (!value) return m.common_never();
-
- const date = new Date(value);
- if (Number.isNaN(date.getTime())) {
- return m.common_unknown();
- }
-
- return formatDateTimeShort(date);
- }
</script>
{#snippet badgeTile(label: string, text: string, variant: BadgeVariant)}
@@ -97,9 +86,18 @@
{#if tunnelTypeBadge}
{@render badgeTile(m.environments_edge_tunnel_type_label(), tunnelTypeBadge.text, tunnelTypeBadge.variant)}
{/if}
- {@render tile(m.environments_edge_connected_since_label(), formatDateTime(environment.connectedAt))}
- {@render tile(m.environments_edge_last_heartbeat_label(), formatDateTime(environment.lastHeartbeat))}
+ {@render tile(
+ m.environments_edge_connected_since_label(),
+ environment.connectedAt ? formatDateTimeShort(environment.connectedAt) || m.common_unknown() : m.common_never()
+ )}
+ {@render tile(
+ m.environments_edge_last_heartbeat_label(),
+ environment.lastHeartbeat ? formatDateTimeShort(environment.lastHeartbeat) || m.common_unknown() : m.common_never()
+ )}
{#if controlPlaneBadge}
- {@render tile(m.environments_edge_last_poll_label(), formatDateTime(environment.lastPollAt))}
+ {@render tile(
+ m.environments_edge_last_poll_label(),
+ environment.lastPollAt ? formatDateTimeShort(environment.lastPollAt) || m.common_unknown() : m.common_never()
+ )}
{/if}
</div>
diff --git a/frontend/src/routes/(app)/environments/[id]/components/EnvironmentStatusSummary.svelte b/frontend/src/routes/(app)/environments/[id]/components/EnvironmentStatusSummary.svelte
index c34cd29d4..f333c6e6f 100644
--- a/frontend/src/routes/(app)/environments/[id]/components/EnvironmentStatusSummary.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/components/EnvironmentStatusSummary.svelte
@@ -1,5 +1,5 @@
<script lang="ts">
- import { formatDistance } from 'date-fns';
+ import { Temporal } from 'temporal-polyfill';
import { Badge } from '#lib/components/ui/badge/index.js';
import { Spinner } from '#lib/components/ui/spinner/index.js';
import { cn } from '#lib/utils';
@@ -8,6 +8,8 @@
import { DetailMetaStrip } from '#lib/components/resource-detail';
import type { Environment, EnvironmentStatus } from '#lib/types/environment';
import type { AppVersionInformation } from '#lib/types/settings';
+ import { formatRelativeTime } from '#lib/utils/formatting';
+ import { createSubscriber } from 'svelte/reactivity';
let {
environment,
@@ -78,29 +80,19 @@
remoteVersion?.displayVersion || remoteVersion?.currentTag || remoteVersion?.currentVersion || ''
);
- function formatRelative(value: string | undefined, base: number): string {
- if (!value) return m.common_never();
-
- const date = new Date(value);
- if (Number.isNaN(date.getTime())) {
- return m.common_unknown();
- }
-
- return formatDistance(date, base, { addSuffix: true });
- }
-
// The relative heartbeat ("2 minutes ago") must keep ticking even when
// lastHeartbeat stops changing (e.g. a silent agent); otherwise it would
- // freeze at the value from the last fetch. Recompute against a ticking base.
- let nowTick = $state(Date.now());
-
- $effect(() => {
- if (!environment.isEdge) return;
- const interval = setInterval(() => (nowTick = Date.now()), 30_000);
+ // freeze at the value from the last fetch. Invalidate its consumer on a timer.
+ const subscribeToHeartbeatClock = createSubscriber((update) => {
+ const interval = setInterval(update, 30_000);
return () => clearInterval(interval);
});
- let heartbeatRelative = $derived(formatRelative(environment.lastHeartbeat, nowTick));
+ let heartbeatRelative = $derived.by(() => {
+ if (!environment.lastHeartbeat) return m.common_never();
+ subscribeToHeartbeatClock();
+ return formatRelativeTime(environment.lastHeartbeat, { base: Temporal.Now.instant() }) || m.common_unknown();
+ });
</script>
<DetailMetaStrip>
diff --git a/frontend/src/routes/(app)/events/event-table.svelte b/frontend/src/routes/(app)/events/event-table.svelte
index 078adc971..0474ba78c 100644
--- a/frontend/src/routes/(app)/events/event-table.svelte
+++ b/frontend/src/routes/(app)/events/event-table.svelte
@@ -7,7 +7,7 @@
import { Badge } from '#lib/components/ui/badge';
import { tryCatch } from '#lib/utils/api';
import { handleApiResultWithCallbacks } from '#lib/utils/api';
- import { formatDistanceToNow } from 'date-fns';
+ import { formatRelativeTime } from '#lib/utils/formatting';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared';
import type { Event } from '#lib/types/shared';
import type { ColumnSpec, MobileFieldVisibility } from '#lib/components/arcane-table';
@@ -187,8 +187,7 @@
variant: eventSeverityIconVariant(item.severity)
})}
title={(item: Event) => item.title}
- subtitle={(item: Event) =>
- (mobileFieldVisibility['timestamp'] ?? true) ? formatDistanceToNow(new Date(item.timestamp), { addSuffix: true }) : null}
+ subtitle={(item: Event) => ((mobileFieldVisibility['timestamp'] ?? true) ? formatRelativeTime(item.timestamp) : null)}
badges={[
(item: Event) =>
(mobileFieldVisibility['severity'] ?? true)
diff --git a/frontend/src/routes/(app)/images/[imageId]/+page.svelte b/frontend/src/routes/(app)/images/[imageId]/+page.svelte
index 07f6ba867..72a843833 100644
--- a/frontend/src/routes/(app)/images/[imageId]/+page.svelte
+++ b/frontend/src/routes/(app)/images/[imageId]/+page.svelte
@@ -2,7 +2,7 @@
import * as Tabs from '#lib/components/ui/tabs/index.js';
import { goto } from '$app/navigation';
import { Badge } from '#lib/components/ui/badge';
- import { bytes, formatDateTimeShort } from '#lib/utils/formatting';
+ import { bytes, formatDateTimeShort, nowInstantString } from '#lib/utils/formatting';
import { openConfirmDialog } from '#lib/components/confirm-dialog';
import { handleApiResultWithCallbacks } from '#lib/utils/api';
import { tryCatch } from '#lib/utils/api';
@@ -93,7 +93,7 @@
try {
const result = await vulnerabilityService.scanImage(image.id);
vulnerabilityScan = result;
- lastScanRequestedAt = result.scanTime || new Date().toISOString();
+ lastScanRequestedAt = result.scanTime || nowInstantString();
if (isVulnerabilityScanInProgress(result.status)) {
toastVulnerabilityScanStatus(result, { includeStarted: true });
beginScanPolling(true);
diff --git a/frontend/src/routes/(app)/images/[imageId]/image-history-panel.svelte b/frontend/src/routes/(app)/images/[imageId]/image-history-panel.svelte
index bddcfba85..35494860e 100644
--- a/frontend/src/routes/(app)/images/[imageId]/image-history-panel.svelte
+++ b/frontend/src/routes/(app)/images/[imageId]/image-history-panel.svelte
@@ -6,6 +6,7 @@
import { imageService } from '#lib/services/image-service';
import type { ImageHistoryItemDto } from '#lib/types/docker';
import { m } from '#lib/paraglide/messages';
+ import { Temporal } from 'temporal-polyfill';
let { imageId }: { imageId: string } = $props();
@@ -33,7 +34,7 @@
function formatCreated(created: number) {
if (!created) return m.common_na();
- return formatDateTimeShort(new Date(created * 1000));
+ return formatDateTimeShort(Temporal.Instant.fromEpochMilliseconds(created * 1000));
}
</script>
diff --git a/frontend/src/routes/(app)/images/image-table.svelte b/frontend/src/routes/(app)/images/image-table.svelte
index 38127c0ea..e879e618e 100644
--- a/frontend/src/routes/(app)/images/image-table.svelte
+++ b/frontend/src/routes/(app)/images/image-table.svelte
@@ -6,7 +6,7 @@
import { goto } from '$app/navigation';
import { onDestroy } from 'svelte';
import { toast } from 'svelte-sonner';
- import { bytes, formatDateTimeShort } from '#lib/utils/formatting';
+ import { bytes, formatDateTimeShort, nowInstantString } from '#lib/utils/formatting';
import { inUseBadge } from '#lib/utils/mobile-card-badges';
import { openConfirmDialog } from '#lib/components/confirm-dialog';
import { Badge } from '#lib/components/ui/badge/index.js';
@@ -32,6 +32,7 @@
import { bulkConfirmAndRun } from '#lib/utils/bulk-actions';
import InUseStatus from '#lib/components/arcane-table/cells/in-use-status.svelte';
import UnixCreatedCell from '#lib/components/arcane-table/cells/unix-created-cell.svelte';
+ import { Temporal } from 'temporal-polyfill';
import {
DownloadIcon,
@@ -197,7 +198,7 @@
message: m.vuln_scan_failed(),
setLoadingState: () => {},
onSuccess: async (data) => {
- scanRequestedAtByImage[imageId] = data.scanTime || new Date().toISOString();
+ scanRequestedAtByImage[imageId] = data.scanTime || nowInstantString();
const summary: VulnerabilityScanSummary = {
imageId: data.imageId,
scanTime: data.scanTime,
@@ -639,7 +640,7 @@
footer={(mobileFieldVisibility['created'] ?? true)
? {
label: m.common_created(),
- getValue: (item) => formatDateTimeShort(new Date(Number(item.created || 0) * 1000)),
+ getValue: (item) => formatDateTimeShort(Temporal.Instant.fromEpochMilliseconds(Number(item.created || 0) * 1000)),
icon: ClockIcon
}
: undefined}
diff --git a/frontend/src/routes/(app)/images/vulnerabilities/ignored-vulnerabilities-table.svelte b/frontend/src/routes/(app)/images/vulnerabilities/ignored-vulnerabilities-table.svelte
index e4e515955..212af8a56 100644
--- a/frontend/src/routes/(app)/images/vulnerabilities/ignored-vulnerabilities-table.svelte
+++ b/frontend/src/routes/(app)/images/vulnerabilities/ignored-vulnerabilities-table.svelte
@@ -5,6 +5,7 @@
import { ShieldAlertIcon, CodeIcon, ImagesIcon, EyeOnIcon } from '#lib/icons';
import { ArcaneButton } from '#lib/components/arcane-button';
import IfPermitted from '#lib/components/if-permitted.svelte';
+ import { formatDate } from '#lib/utils/formatting';
let {
ignoredVulnerabilities,
@@ -22,11 +23,6 @@
const DEFAULT_PAGE_SIZE = 20;
- function formatDate(dateString: string): string {
- const date = new Date(dateString);
- return date.toLocaleDateString();
- }
-
function handlePageChange(page: number) {
const newOptions: SearchPaginationSortRequest = {
...requestOptions,
@@ -77,7 +73,7 @@
{item.imageId.substring(0, 12)}...
</span>
</span>
- <span>• {formatDate(item.createdAt)}</span>
+ <span>• {formatDate(item.createdAt) || m.common_unknown()}</span>
</div>
{#if item.reason}
<div class="text-xs text-muted-foreground italic">
diff --git a/frontend/src/routes/(app)/settings/diagnostics/+page.svelte b/frontend/src/routes/(app)/settings/diagnostics/+page.svelte
index cf5a7556a..31a2d3727 100644
--- a/frontend/src/routes/(app)/settings/diagnostics/+page.svelte
+++ b/frontend/src/routes/(app)/settings/diagnostics/+page.svelte
@@ -36,7 +36,7 @@
let connected = $state(false);
let paused = $state(false);
let lastUpdated = $state(0);
- let now = $state(Date.now());
+ let now = $state(performance.now());
let error = $state<string | null>(null);
let ws: ReconnectingWebSocket<Diagnostics> | null = null;
@@ -209,7 +209,7 @@
function applySnapshot(d: Diagnostics) {
diag = d;
- lastUpdated = Date.now();
+ lastUpdated = performance.now();
error = null;
}
@@ -301,7 +301,7 @@
onMount(() => {
refresh();
openStream();
- tick = setInterval(() => (now = Date.now()), 1000);
+ tick = setInterval(() => (now = performance.now()), 1000);
return () => {
closeStream();
if (tick) clearInterval(tick);
diff --git a/frontend/src/routes/(app)/swarm/services/components/ServiceOverview.svelte b/frontend/src/routes/(app)/swarm/services/components/ServiceOverview.svelte
index 9bd689f1d..d9f5ae9b6 100644
--- a/frontend/src/routes/(app)/swarm/services/components/ServiceOverview.svelte
+++ b/frontend/src/routes/(app)/swarm/services/components/ServiceOverview.svelte
@@ -3,9 +3,8 @@
import { Badge } from '#lib/components/ui/badge';
import { m } from '#lib/paraglide/messages';
import type { SwarmServiceInspect } from '#lib/types/swarm';
- import { formatDistanceToNow } from 'date-fns';
import { InfoIcon, ConnectionIcon } from '#lib/icons';
- import { formatDateTimeShort, truncateImageDigest } from '#lib/utils/formatting';
+ import { formatDateTimeShort, formatRelativeTime, truncateImageDigest } from '#lib/utils/formatting';
import {
SWARM_STACK_LABEL,
getSwarmServiceModeLabel,
@@ -25,20 +24,6 @@
let { service, serviceName, serviceImage, serviceMode, desiredReplicas, labels }: Props = $props();
- function formatDate(input: string | undefined | null): string {
- if (!input) return m.common_na();
- return formatDateTimeShort(input) || m.common_na();
- }
-
- function formatRelative(input: string | undefined | null): string {
- if (!input) return m.common_na();
- try {
- return formatDistanceToNow(new Date(input), { addSuffix: true });
- } catch {
- return m.common_na();
- }
- }
-
const stackName = $derived(labels?.[SWARM_STACK_LABEL] || '');
const nodes = $derived((service?.nodes as string[]) || []);
const versionIndex = $derived(service?.version?.index ?? service?.version?.Index ?? 0);
@@ -122,10 +107,10 @@
{m.common_created()}
</div>
<div class="text-sm font-medium text-foreground">
- {formatRelative(service.createdAt)}
+ {formatRelativeTime(service.createdAt) || m.common_na()}
</div>
<div class="text-xs text-muted-foreground">
- {formatDate(service.createdAt)}
+ {formatDateTimeShort(service.createdAt) || m.common_na()}
</div>
</Card.Content>
</Card.Root>
@@ -136,10 +121,10 @@
{m.common_updated()}
</div>
<div class="text-sm font-medium text-foreground">
- {formatRelative(service.updatedAt)}
+ {formatRelativeTime(service.updatedAt) || m.common_na()}
</div>
<div class="text-xs text-muted-foreground">
- {formatDate(service.updatedAt)}
+ {formatDateTimeShort(service.updatedAt) || m.common_na()}
</div>
</Card.Content>
</Card.Root>
@@ -185,7 +170,7 @@
</div>
{#if updateStatus['CompletedAt']}
<div class="text-xs text-muted-foreground">
- {formatRelative(updateStatus['CompletedAt'])}
+ {formatRelativeTime(String(updateStatus['CompletedAt'])) || m.common_na()}
</div>
{/if}
</Card.Content>
diff --git a/frontend/src/routes/(app)/swarm/stacks/stacks-table.svelte b/frontend/src/routes/(app)/swarm/stacks/stacks-table.svelte
index 153813b20..57c5c7615 100644
--- a/frontend/src/routes/(app)/swarm/stacks/stacks-table.svelte
+++ b/frontend/src/routes/(app)/swarm/stacks/stacks-table.svelte
@@ -7,7 +7,7 @@
import { swarmService } from '#lib/services/swarm-service';
import type { SwarmStackSummary } from '#lib/types/swarm';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared';
- import { formatDistanceToNow } from 'date-fns';
+ import { formatRelativeTime } from '#lib/utils/formatting';
import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
import { openConfirmDialog } from '#lib/components/confirm-dialog';
@@ -27,11 +27,6 @@
let isLoading = $state(false);
- function formatTimestamp(timestamp: string) {
- if (!timestamp) return m.common_unknown();
- return formatDistanceToNow(new Date(timestamp), { addSuffix: true });
- }
-
function inspectStack(stack: SwarmStackSummary) {
goto(`/swarm/stacks/${encodeURIComponent(stack.name)}`);
}
@@ -82,11 +77,11 @@
{/snippet}
{#snippet CreatedCell({ value }: { value: unknown })}
- <span class="text-sm">{formatTimestamp(String(value ?? ''))}</span>
+ <span class="text-sm">{formatRelativeTime(String(value ?? '')) || m.common_unknown()}</span>
{/snippet}
{#snippet UpdatedCell({ value }: { value: unknown })}
- <span class="text-sm">{formatTimestamp(String(value ?? ''))}</span>
+ <span class="text-sm">{formatRelativeTime(String(value ?? '')) || m.common_unknown()}</span>
{/snippet}
{#snippet StackMobileCardSnippet({
@@ -104,7 +99,7 @@
})}
title={(item: SwarmStackSummary) => item.name}
subtitle={(item: SwarmStackSummary) =>
- (mobileFieldVisibility['createdAt'] ?? true) ? formatTimestamp(item.createdAt) : null}
+ (mobileFieldVisibility['createdAt'] ?? true) ? formatRelativeTime(item.createdAt) || m.common_unknown() : null}
fields={[
{
label: m.services(),
@@ -115,7 +110,7 @@
},
{
label: m.common_updated(),
- getValue: (item: SwarmStackSummary) => formatTimestamp(item.updatedAt),
+ getValue: (item: SwarmStackSummary) => formatRelativeTime(item.updatedAt) || m.common_unknown(),
icon: LayersIcon,
iconVariant: 'gray' as const,
show: mobileFieldVisibility['updatedAt'] ?? false
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 19b7239b5..9d5749a2c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -174,9 +174,6 @@ importers:
clsx:
specifier: ^2.1.1
version: 2.1.1
- date-fns:
- specifier: ^4.4.0
- version: 4.4.0
embla-carousel-svelte:
specifier: ^8.6.0
version: 8.6.0([email protected])
@@ -213,6 +210,9 @@ importers:
tailwind-variants:
specifier: ^3.3.1
+ temporal-polyfill:
+ specifier: ^1.0.4
+ version: 1.0.4
vaul-svelte:
specifier: 1.0.0-next.7
version: 1.0.0-next.7([email protected])
@@ -2330,9 +2330,6 @@ packages:
resolution: {integrity: sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==}
engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
- resolution: {integrity: sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==}
-
resolution: {integrity: sha512-98IT+HOahAisibz/yjKbzuOBwYcjJ7BCLPzARyHiyEBmRz4fatF+KPJszEHXsGYjUG234aH/cOjW1wwTbKUZlA==}
@@ -3267,6 +3264,15 @@ packages:
resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-MLEU0qOD2uXlz24oINNtdLZQl8RgmMxSnRtKEGZGGetTJjlRwQJjk+VsJ4EREaUoiaTb8NJOcUiKtoAiWn9EBg==}
+
+ resolution: {integrity: sha512-wxVoanmDeavXie1vu2JaQ3WIc3JZnWAOYFBsJyATaVsXsycKYUflGsyBmrRSnoCpZJpwPyr38VpgSUlQ8CbFxg==}
+
+ resolution: {integrity: sha512-1B8Dl4KzrOvsNUlpoWGno2VLQlxroLjDgc5NBjVC9ax9ymdo+ezfyvhyjEMx+IVfhINr6CIG2gcnlP95iRrybQ==}
+
resolution: {integrity: sha512-Eet/eeMhkO6TX8mnUteS9zgPbUMQa4I6Kkp5ORiBD5476/m+PIRiumP5tmh5ioJpH7k51Kehawy2UDfsnxxY8Q==}
@@ -4725,24 +4731,24 @@ snapshots:
validator: 13.15.35
optional: true
dependencies:
'@testing-library/dom': 10.4.1
'@testing-library/user-event': 14.6.3(@testing-library/[email protected])
transitivePeerDependencies:
- bufferutil
- msw
- utf-8-validate
- vite
dependencies:
'@testing-library/dom': 10.4.1
'@testing-library/user-event': 14.6.3(@testing-library/[email protected])
transitivePeerDependencies:
- bufferutil
- msw
@@ -4761,7 +4767,7 @@ snapshots:
- utf-8-validate
- vite
dependencies:
'@blazediff/core': 1.9.1
@@ -4770,7 +4776,7 @@ snapshots:
pngjs: 7.0.0
sirv: 3.0.2
tinyrainbow: 3.1.1
ws: 8.21.1
transitivePeerDependencies:
- bufferutil
@@ -4778,7 +4784,7 @@ snapshots:
- utf-8-validate
- vite
dependencies:
'@blazediff/core': 1.9.1
@@ -4787,7 +4793,7 @@ snapshots:
pngjs: 7.0.0
sirv: 3.0.2
tinyrainbow: 3.1.1
ws: 8.21.1
transitivePeerDependencies:
- bufferutil
@@ -5258,8 +5264,6 @@ snapshots:
transitivePeerDependencies:
- '@noble/hashes'
-
optional: true
@@ -6360,6 +6364,15 @@ snapshots:
+ dependencies:
+ temporal-spec: 1.0.1
+ temporal-utils: 1.0.2
+
+
+
optional: true
@@ -6503,8 +6516,8 @@ snapshots:
dependencies:
'@oxc-project/types': 0.143.0
'@oxlint/plugins': 1.73.0
'@vitest/expect': 4.1.10
'@vitest/pretty-format': 4.1.10
@@ -6516,7 +6529,7 @@ snapshots:
oxlint-tsgolint: 7.0.2001
optionalDependencies:
'@voidzero-dev/vite-plus-darwin-arm64': 0.2.9
'@voidzero-dev/vite-plus-darwin-x64': 0.2.9
@@ -6561,8 +6574,8 @@ snapshots:
dependencies:
'@oxc-project/types': 0.143.0
'@oxlint/plugins': 1.73.0
'@vitest/expect': 4.1.10
'@vitest/pretty-format': 4.1.10
@@ -6574,7 +6587,7 @@ snapshots:
oxlint-tsgolint: 7.0.2001
optionalDependencies:
'@voidzero-dev/vite-plus-darwin-arm64': 0.2.9
'@voidzero-dev/vite-plus-darwin-x64': 0.2.9
@@ -6677,7 +6690,7 @@ snapshots:
optionalDependencies:
dependencies:
'@vitest/expect': 4.1.10
@@ -6701,12 +6714,12 @@ snapshots:
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 26.2.0
jsdom: 30.0.1
transitivePeerDependencies:
- msw
dependencies:
'@vitest/expect': 4.1.10
@@ -6730,7 +6743,7 @@ snapshots:
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 26.2.0
jsdom: 30.0.1
transitivePeerDependencies:
- msw