feat: configurable date/time display (fixed time zone + format patterns)

- pageConfig.dateTime.timeZone: optional fixed IANA time zone; default is
  the visitor's local time. Visitors in a different zone get an info icon
  with a notice next to "Last updated" (translated in all locales)
- pageConfig.dateTime.formats: moment-style patterns for dateTime, date
  and time; unset patterns keep the previous formatting
- Applied to Last updated, daily bar tooltips and incident modal,
  maintenance alerts, incidents page month grouping, response-time chart
  axis/tooltip, and notification messages (in notification.timeZone)
- Daily bars and incident months follow the configured time zone
- Default notification format now includes the year
- English strings: "on {{date}}" instead of "at {{date}}"
- util/datetime.ts: dependency-free Intl-based formatter shared by the
  page and the worker
pull/226/head
stoilms 2026-10-20 14:55:56 +03:00
parent 520c0b8dcf
commit 43d48d654c
15 changed files with 322 additions and 33 deletions

View File

@ -4,6 +4,7 @@ import { Box, Tooltip, Modal } from '@mantine/core'
import { useResizeObserver } from '@mantine/hooks'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useDateTime } from '@/util/useDateTime'
const moment = require('moment')
require('moment-precise-range-plugin')
@ -15,6 +16,7 @@ export default function DetailBar({
state: MonitorState
}) {
const { t } = useTranslation('common')
const dateTime = useDateTime()
const [barRef, barRect] = useResizeObserver()
const [modalOpened, setModalOpened] = useState(false)
const [modalTitle, setModalTitle] = useState('')
@ -29,11 +31,11 @@ export default function DetailBar({
const currentTime = Math.round(Date.now() / 1000)
const montiorStartTime = state.incident[monitor.id][0].start[0]
const todayStart = new Date()
todayStart.setHours(0, 0, 0, 0)
// Day boundaries follow the configured time zone (or the viewer's local one)
const todayStart = dateTime.startOfDay(currentTime)
for (let i = 89; i >= 0; i--) {
const dayStart = Math.round(todayStart.getTime() / 1000) - i * 86400
const dayStart = todayStart - i * 86400
const dayEnd = dayStart + 86400
const dayMonitorTime = overlapLen(dayStart, dayEnd, montiorStartTime, currentTime)
@ -58,14 +60,8 @@ export default function DetailBar({
partEnd = Math.min(partEnd, dayEnd)
if (overlapLen(dayStart, dayEnd, partStart, partEnd) > 0) {
const startStr = new Date(partStart * 1000).toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
})
const endStr = new Date(partEnd * 1000).toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
})
const startStr = dateTime.format('time', partStart * 1000)
const endStr = dateTime.format('time', partEnd * 1000)
incidentReasons.push(`[${startStr}-${endStr}] ${incident.error[i]}`)
}
}
@ -87,7 +83,7 @@ export default function DetailBar({
<div>
{t('percent at date', {
percent: dayPercent,
date: new Date(dayStart * 1000).toLocaleDateString(),
date: dateTime.format('date', dayStart * 1000),
})}
</div>
{dayDownTime > 0 && (
@ -115,7 +111,7 @@ export default function DetailBar({
setModalTitle(
t('incidents at', {
name: monitor.name,
date: new Date(dayStart * 1000).toLocaleDateString(),
date: dateTime.format('date', dayStart * 1000),
})
)
setModelContent(

View File

@ -14,6 +14,8 @@ import 'chartjs-adapter-moment'
import { MonitorState, MonitorTarget } from '@/types/config'
import { codeToCountry } from '@/util/iata'
import { useTranslation } from 'react-i18next'
import { pageConfig } from '@/uptime.config'
import { useDateTime } from '@/util/useDateTime'
ChartJS.register(
CategoryScale,
@ -34,6 +36,9 @@ export default function DetailChart({
state: MonitorState
}) {
const { t } = useTranslation('common')
const dateTime = useDateTime()
// Only override chart.js's own time labels when date/time display is configured
const customTimes = pageConfig.dateTime !== undefined
const latencyData = state.latency[monitor.id].map((point) => ({
x: point.time * 1000,
y: point.ping,
@ -66,6 +71,10 @@ export default function DetailChart({
plugins: {
tooltip: {
callbacks: {
...(customTimes && {
title: (items: any[]) =>
items.length ? dateTime.format('dateTime', items[0].parsed.x) : '',
}),
label: (item: any) => {
if (item.parsed.y) {
return `${item.parsed.y}ms (${codeToCountry(item.raw.loc)})`
@ -89,6 +98,9 @@ export default function DetailChart({
source: 'auto' as const,
maxRotation: 0,
autoSkip: true,
...(customTimes && {
callback: (value: string | number) => dateTime.format('time', value),
}),
},
},
},

View File

@ -4,6 +4,7 @@ import { IconAlertTriangle } from '@tabler/icons-react'
import { MaintenanceConfig, MonitorTarget } from '@/types/config'
import { pageConfig } from '@/uptime.config'
import { useTranslation } from 'react-i18next'
import { useDateTime } from '@/util/useDateTime'
export default function MaintenanceAlert({
maintenance,
@ -15,6 +16,7 @@ export default function MaintenanceAlert({
upcoming?: boolean
}) {
const { t } = useTranslation('common')
const dateTime = useDateTime()
const theme = useMantineTheme()
const isDesktop = useMediaQuery(`(min-width: ${theme.breakpoints.sm})`)
@ -65,13 +67,13 @@ export default function MaintenanceAlert({
<div style={{ textAlign: 'right', fontWeight: 'bold' }}>
{upcoming ? t('Scheduled for') : t('From')}
</div>
<div>{new Date(maintenance.start).toLocaleString()}</div>
<div>{dateTime.format('dateTime', maintenance.start)}</div>
<div style={{ textAlign: 'right', fontWeight: 'bold' }}>
{upcoming ? t('Expected end') : t('To')}
</div>
<div>
{maintenance.end
? new Date(maintenance.end).toLocaleString()
? dateTime.format('dateTime', maintenance.end)
: t('Until further notice')}
</div>
</div>

View File

@ -1,10 +1,17 @@
import { MaintenanceConfig, MonitorTarget } from '@/types/config'
import { Center, Container, Title, Collapse, Button, Box } from '@mantine/core'
import { IconCircleCheck, IconAlertCircle, IconPlus, IconMinus } from '@tabler/icons-react'
import { Center, Container, Title, Collapse, Button, Box, Tooltip } from '@mantine/core'
import {
IconCircleCheck,
IconAlertCircle,
IconPlus,
IconMinus,
IconInfoCircle,
} from '@tabler/icons-react'
import { useEffect, useState } from 'react'
import MaintenanceAlert from './MaintenanceAlert'
import { pageConfig } from '@/uptime.config'
import { useTranslation } from 'react-i18next'
import { useDateTime, useTimeZoneNotice } from '@/util/useDateTime'
function useWindowVisibility() {
const [isVisible, setIsVisible] = useState(true)
@ -26,6 +33,8 @@ export default function OverallStatus({
monitors: MonitorTarget[]
}) {
const { t } = useTranslation('common')
const dateTime = useDateTime()
const timeZoneNotice = useTimeZoneNotice()
let group = pageConfig.group
let groupedMonitor = (group && Object.keys(group).length > 0) || false
@ -93,9 +102,17 @@ export default function OverallStatus({
</Title>
<Title mt="sm" style={{ textAlign: 'center', color: '#70778c' }} order={5}>
{t('Last updated on', {
date: new Date(state.lastUpdate * 1000).toLocaleString(),
date: dateTime.format('dateTime', state.lastUpdate * 1000),
seconds: currentTime - state.lastUpdate,
})}
{timeZoneNotice && (
<Tooltip label={t('Times shown in time zone', timeZoneNotice)} multiline maw={300}>
<IconInfoCircle
aria-label={t('Times shown in time zone', timeZoneNotice)}
style={{ width: 16, height: 16, marginLeft: 4, verticalAlign: 'text-bottom' }}
/>
</Tooltip>
)}
</Title>
{/* Upcoming Maintenance */}

View File

@ -33,5 +33,6 @@
"All": "Alle",
"Select monitor": "Auswählen",
"Backwards": "← Zurück",
"Forward": "Vorwärts →"
"Forward": "Vorwärts →",
"Times shown in time zone": "Zeiten werden in {{timeZone}} ({{offset}}) angezeigt, nicht in Ihrer lokalen Zeitzone"
}

View File

@ -13,9 +13,9 @@
"No data available": "No data available, please make sure you have deployed your workers with latest config and check your worker status!",
"Overall": "Overall: {{percent}}%",
"No Data": "No Data",
"percent at date": "{{percent}}% at {{date}}",
"percent at date": "{{percent}}% on {{date}}",
"Down for": "Down for {{duration}} (click for detail)",
"incidents at": "🚨 {{name}} incidents at {{date}}",
"incidents at": "🚨 {{name}} incidents on {{date}}",
"Response times": "Response times(ms)",
"Upcoming": "[Upcoming] ",
"Scheduled Maintenance": "Scheduled Maintenance",
@ -33,5 +33,6 @@
"All": "All",
"Select monitor": "Select monitor",
"Backwards": "← Backwards",
"Forward": "Forward →"
"Forward": "Forward →",
"Times shown in time zone": "Times are shown in {{timeZone}} ({{offset}}), not your local time zone"
}

View File

@ -33,5 +33,6 @@
"All": "Tous",
"Select monitor": "Sélectionner un moniteur",
"Backwards": "← Précédent",
"Forward": "Suivant →"
"Forward": "Suivant →",
"Times shown in time zone": "Les heures sont affichées dans le fuseau {{timeZone}} ({{offset}}), et non dans votre fuseau horaire local"
}

View File

@ -33,5 +33,6 @@
"All": "全部",
"Select monitor": "选择监控",
"Backwards": "← 上一月",
"Forward": "下一月 →"
"Forward": "下一月 →",
"Times shown in time zone": "时间以 {{timeZone}} ({{offset}}) 显示,而非您的本地时区"
}

View File

@ -33,5 +33,6 @@
"All": "全部",
"Select monitor": "選取站點",
"Backwards": "← 上個月",
"Forward": "下個月 →"
"Forward": "下個月 →",
"Times shown in time zone": "時間以 {{timeZone}} ({{offset}}) 顯示,而非您的本地時區"
}

View File

@ -10,15 +10,18 @@ import { useEffect, useState } from 'react'
import MaintenanceAlert from '@/components/MaintenanceAlert'
import NoIncidentsAlert from '@/components/NoIncidents'
import { useTranslation } from 'react-i18next'
import { yearMonth } from '@/util/datetime'
export const runtime = 'experimental-edge'
const inter = Inter({ subsets: ['latin'] })
// Months follow the configured time zone (or the viewer's local one)
const timeZone = pageConfig.dateTime?.timeZone
function getSelectedMonth() {
const hash = window.location.hash.replace('#', '')
if (!hash) {
const now = new Date()
return now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0')
return yearMonth(new Date(), timeZone)
}
return hash.split('-').splice(0, 2).join('-')
}
@ -30,9 +33,7 @@ function filterIncidentsByMonth(
): (Omit<MaintenanceConfig, 'monitors'> & { monitors: MonitorTarget[] })[] {
return incidents
.filter((incident) => {
const d = new Date(incident.start)
const incidentMonth = d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0')
return incidentMonth === monthStr
return yearMonth(new Date(incident.start), timeZone) === monthStr
})
.map((e) => ({
...e,

View File

@ -1,4 +1,5 @@
import type { Env } from '../worker/src'
import type { DateTimeConfig } from '../util/datetime'
export type PageConfig = {
title?: string
@ -10,6 +11,7 @@ export type PageConfig = {
upcomingColor?: string
}
customFooter?: string
dateTime?: DateTimeConfig
}
export type MaintenanceConfig = {

View File

@ -28,6 +28,21 @@ const pageConfig: PageConfig = {
},
// [OPTIONAL] Custom footer html
// customFooter: '',
// [OPTIONAL] Date/time display on the status page (also used by notification messages)
// dateTime: {
// // [OPTIONAL] IANA time zone shown to every visitor, default to each visitor's local time zone
// // Visitors in a different time zone get a notice next to "Last updated"
// // (notifications keep using `notification.timeZone`)
// timeZone: 'Asia/Shanghai',
// // [OPTIONAL] moment-style patterns, each one defaults to the browser's locale format if not specified
// // Tokens: YYYY YY MMMM MMM MM M DD D dddd ddd HH H hh h mm m ss s A a z, [literal text]
// // Month/weekday names and AM/PM follow the page language (English in notifications)
// formats: {
// dateTime: 'MMM D, YYYY [at] h:mm:ss A', // e.g. "Jul 25, 2025 at 3:12:34 AM"
// date: 'MMM D, YYYY', // daily bars, incidents
// time: 'HH:mm', // incident time ranges
// },
// },
}
const workerConfig: WorkerConfig = {

185
util/datetime.ts Normal file
View File

@ -0,0 +1,185 @@
// Configurable date/time formatting, shared by the status page and the worker.
// Built on Intl only (no dependencies), so any IANA time zone works in browsers and Workers.
export type DateTimeKind = 'dateTime' | 'date' | 'time'
export type DateTimeFormats = { [kind in DateTimeKind]?: string }
export type DateTimeConfig = {
// IANA time zone, e.g. 'Europe/Sofia'. Unset: the viewer's local time zone
timeZone?: string
// moment-style patterns, e.g. 'MMM D, YYYY [at] h:mm:ss A'. Unset: legacy formatting
formats?: DateTimeFormats
}
type FormatOptions = {
timeZone?: string
// Locale used for month/weekday names, AM/PM and zone names only. Default 'en-US'
locale?: string
}
const TOKEN_REGEX = /\[([^\]]*)\]|YYYY|YY|MMMM|MMM|MM|M|DD|D|dddd|ddd|HH|H|hh|h|mm|m|ss|s|A|a|z/g
const formatterCache = new Map<string, Intl.DateTimeFormat>()
function getFormatter(locale: string, options: Intl.DateTimeFormatOptions) {
const key = locale + JSON.stringify(options)
let formatter = formatterCache.get(key)
if (!formatter) {
formatter = new Intl.DateTimeFormat(locale, options)
formatterCache.set(key, formatter)
}
return formatter
}
function getPart(
date: Date,
locale: string,
options: Intl.DateTimeFormatOptions,
type: Intl.DateTimeFormatPartTypes
) {
return getFormatter(locale, options)
.formatToParts(date)
.find((p) => p.type === type)?.value
}
// Numeric calendar fields of `date` as seen in `timeZone`
function getFields(date: Date, timeZone?: string) {
const parts = getFormatter('en-US', {
timeZone,
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hourCycle: 'h23',
}).formatToParts(date)
const get = (type: Intl.DateTimeFormatPartTypes) =>
Number(parts.find((p) => p.type === type)?.value)
return {
year: get('year'),
month: get('month'),
day: get('day'),
hour: get('hour') % 24,
minute: get('minute'),
second: get('second'),
}
}
const pad = (n: number, len = 2) => String(n).padStart(len, '0')
export function formatPattern(date: Date, pattern: string, options: FormatOptions = {}): string {
const { timeZone } = options
const locale = options.locale || 'en-US'
const f = getFields(date, timeZone)
const hour12 = f.hour % 12 || 12
return pattern.replace(TOKEN_REGEX, (token, literal) => {
if (literal !== undefined) return literal
switch (token) {
case 'YYYY':
return String(f.year)
case 'YY':
return pad(f.year % 100)
case 'MMMM':
return getPart(date, locale, { timeZone, month: 'long' }, 'month') ?? pad(f.month)
case 'MMM':
return getPart(date, locale, { timeZone, month: 'short' }, 'month') ?? pad(f.month)
case 'MM':
return pad(f.month)
case 'M':
return String(f.month)
case 'DD':
return pad(f.day)
case 'D':
return String(f.day)
case 'dddd':
return getPart(date, locale, { timeZone, weekday: 'long' }, 'weekday') ?? ''
case 'ddd':
return getPart(date, locale, { timeZone, weekday: 'short' }, 'weekday') ?? ''
case 'HH':
return pad(f.hour)
case 'H':
return String(f.hour)
case 'hh':
return pad(hour12)
case 'h':
return String(hour12)
case 'mm':
return pad(f.minute)
case 'm':
return String(f.minute)
case 'ss':
return pad(f.second)
case 's':
return String(f.second)
case 'A':
case 'a': {
const period =
getPart(date, locale, { timeZone, hour: 'numeric', hour12: true }, 'dayPeriod') ??
(f.hour < 12 ? 'AM' : 'PM')
return token === 'a' ? period.toLowerCase() : period
}
case 'z':
return getPart(date, locale, { timeZone, timeZoneName: 'short' }, 'timeZoneName') ?? ''
}
return token
})
}
// Formatting used when no pattern is configured (the behaviour before patterns existed)
function legacyFormat(kind: DateTimeKind, date: Date, timeZone?: string) {
switch (kind) {
case 'dateTime':
return date.toLocaleString(undefined, { timeZone })
case 'date':
return date.toLocaleDateString(undefined, { timeZone })
case 'time':
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', timeZone })
}
}
export function formatDateTime(
kind: DateTimeKind,
date: Date | number | string,
config: DateTimeConfig | undefined,
locale?: string
): string {
const d = date instanceof Date ? date : new Date(date)
const pattern = config?.formats?.[kind]
if (!pattern) return legacyFormat(kind, d, config?.timeZone)
return formatPattern(d, pattern, { timeZone: config?.timeZone, locale })
}
// Offset of `timeZone` from UTC at `date`, in minutes (e.g. 180 for Europe/Sofia in summer)
export function getTimeZoneOffset(date: Date, timeZone?: string): number {
const f = getFields(date, timeZone)
const asUtc = Date.UTC(f.year, f.month - 1, f.day, f.hour, f.minute, f.second)
return Math.round((asUtc - Math.floor(date.getTime() / 1000) * 1000) / 60000)
}
// e.g. "UTC+3", "UTC-9:30", "UTC"
export function formatUtcOffset(offsetMinutes: number): string {
if (offsetMinutes === 0) return 'UTC'
const sign = offsetMinutes > 0 ? '+' : '-'
const abs = Math.abs(offsetMinutes)
const minutes = abs % 60
return `UTC${sign}${Math.floor(abs / 60)}${minutes ? ':' + pad(minutes) : ''}`
}
// Unix timestamp (seconds) of the start of the day containing `timestamp`, in `timeZone`
export function startOfDay(timestamp: number, timeZone?: string): number {
const f = getFields(new Date(timestamp * 1000), timeZone)
const midnightAsUtc = Date.UTC(f.year, f.month - 1, f.day) / 1000
// Correct by the zone's offset at that moment; re-check once for DST transitions
let result = midnightAsUtc - getTimeZoneOffset(new Date(midnightAsUtc * 1000), timeZone) * 60
result = midnightAsUtc - getTimeZoneOffset(new Date(result * 1000), timeZone) * 60
return result
}
// "YYYY-MM" of `date` in `timeZone`
export function yearMonth(date: Date, timeZone?: string): string {
const f = getFields(date, timeZone)
return f.year + '-' + pad(f.month)
}

46
util/useDateTime.ts Normal file
View File

@ -0,0 +1,46 @@
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { pageConfig } from '@/uptime.config'
import {
DateTimeKind,
formatDateTime,
formatUtcOffset,
getTimeZoneOffset,
startOfDay,
yearMonth,
} from './datetime'
// Date/time helpers for page components, applying `pageConfig.dateTime`
export function useDateTime() {
const { i18n } = useTranslation('common')
const config = pageConfig.dateTime
const timeZone = config?.timeZone
const locale = i18n.resolvedLanguage || 'en'
return {
timeZone,
format: (kind: DateTimeKind, date: Date | number | string) =>
formatDateTime(kind, date, config, locale),
startOfDay: (timestamp: number) => startOfDay(timestamp, timeZone),
yearMonth: (date: Date) => yearMonth(date, timeZone),
}
}
// When a fixed time zone is configured and differs from the viewer's, returns e.g.
// { timeZone: 'Europe/Sofia', offset: 'UTC+3' }; otherwise null.
// Evaluated after mount, as the viewer's zone is unknown during server rendering.
export function useTimeZoneNotice() {
const timeZone = pageConfig.dateTime?.timeZone
const [notice, setNotice] = useState<{ timeZone: string; offset: string } | null>(null)
useEffect(() => {
if (!timeZone) return
const now = new Date()
const configuredOffset = getTimeZoneOffset(now, timeZone)
if (configuredOffset !== getTimeZoneOffset(now)) {
setNotice({ timeZone, offset: formatUtcOffset(configuredOffset) })
}
}, [timeZone])
return notice
}

View File

@ -1,5 +1,6 @@
import { MonitorTarget, WebhookConfig } from '../../types/config'
import { maintenances, workerConfig } from '../../uptime.config'
import { maintenances, pageConfig, workerConfig } from '../../uptime.config'
import { formatPattern } from '../../util/datetime'
async function getWorkerLocation() {
const res = await fetch('https://cloudflare.com/cdn-cgi/trace')
@ -37,7 +38,10 @@ function formatStatusChangeNotification(
reason: string,
timeZone: string
) {
// Uses the status page's `dateTime` pattern if configured, in the notification time zone
const pattern = pageConfig.dateTime?.formats?.dateTime
const dateFormatter = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'numeric',
day: '2-digit',
hour: '2-digit',
@ -45,10 +49,14 @@ function formatStatusChangeNotification(
hour12: false,
timeZone: timeZone,
})
const formatTime = (timestamp: number) =>
pattern
? formatPattern(new Date(timestamp * 1000), pattern, { timeZone })
: dateFormatter.format(new Date(timestamp * 1000))
let downtimeDuration = Math.round((timeNow - timeIncidentStart) / 60)
const timeNowFormatted = dateFormatter.format(new Date(timeNow * 1000))
const timeIncidentStartFormatted = dateFormatter.format(new Date(timeIncidentStart * 1000))
const timeNowFormatted = formatTime(timeNow)
const timeIncidentStartFormatted = formatTime(timeIncidentStart)
if (isUp) {
return `✅ ${monitor.name} is up! \nThe service is up again after being down for ${downtimeDuration} minutes.`