From 03bb1e57116263b3af43452977effc737173ff5d Mon Sep 17 00:00:00 2001 From: Xinyu Kuo Date: Sat, 7 Mar 2026 23:48:31 +0800 Subject: [PATCH] feat(date-time-converter): implement timezone conversion and add timezone tests (#333) Fix DST-related timezone conversion issues in date-time-converter and normalize timezone handling to canonical IANA timezone names. --- .../date-time-converter.e2e.spec.ts | 49 ++++++++- .../date-time-converter.timezones.test.ts | 64 +++++++++++ .../date-time-converter.timezones.ts | 100 ++++++++++++++++++ .../date-time-converter.vue | 26 ++--- 4 files changed, 226 insertions(+), 13 deletions(-) create mode 100644 src/tools/date-time-converter/date-time-converter.timezones.test.ts create mode 100644 src/tools/date-time-converter/date-time-converter.timezones.ts diff --git a/src/tools/date-time-converter/date-time-converter.e2e.spec.ts b/src/tools/date-time-converter/date-time-converter.e2e.spec.ts index dd5ed779..574a5728 100644 --- a/src/tools/date-time-converter/date-time-converter.e2e.spec.ts +++ b/src/tools/date-time-converter/date-time-converter.e2e.spec.ts @@ -1,6 +1,17 @@ +import type { Page } from '@playwright/test'; import { expect, test } from '@playwright/test'; -test.describe('Date time converter - json to yaml', () => { +const timezoneOutput = '.n-dynamic-input input[readonly]'; + +async function openConverterWithTimezone(page: Page, timezone: string) { + await page.addInitScript(({ timezone }: { timezone: string }) => { + localStorage.setItem('date-time-converter:timezones', JSON.stringify([{ name: timezone }])); + }, { timezone }); + + await page.goto('/date-converter'); +} + +test.describe('Date time converter', () => { test.beforeEach(async ({ page }) => { await page.goto('/date-converter'); }); @@ -32,4 +43,40 @@ test.describe('Date time converter - json to yaml', () => { expect((await page.getByTestId('Mongo ObjectID').inputValue()).trim()).toEqual('64371e400000000000000000'); expect((await page.getByTestId('Excel date/time').inputValue()).trim()).toEqual('45028.88222222222'); }); + + test.describe('DST-aware timezone conversion', () => { + test.beforeEach(async ({ page }) => { + await page.goto('about:blank'); + }); + + [ + { + expected: '2026-03-08T03:30:00-04:00', + input: '2026-03-08T07:30:00Z', + timezone: 'America/New_York', + }, + { + expected: '2026-04-15T13:30:00+01:00', + input: '2026-04-15T12:30:00Z', + timezone: 'Europe/London', + }, + { + expected: '2026-10-04T03:30:00+11:00', + input: '2026-10-03T16:30:00Z', + timezone: 'Australia/Sydney', + }, + { + expected: '2026-03-08T03:30:00-07:00', + input: '2026-03-08T10:30:00Z', + timezone: 'America/Los_Angeles', + }, + ].forEach(({ expected, input, timezone }) => { + test(`uses the correct DST offset for ${timezone}`, async ({ page }) => { + await openConverterWithTimezone(page, timezone); + await page.getByTestId('date-time-converter-input').fill(input); + + await expect(page.locator(timezoneOutput).first()).toHaveValue(expected); + }); + }); + }); }); diff --git a/src/tools/date-time-converter/date-time-converter.timezones.test.ts b/src/tools/date-time-converter/date-time-converter.timezones.test.ts new file mode 100644 index 00000000..9791017f --- /dev/null +++ b/src/tools/date-time-converter/date-time-converter.timezones.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, test } from 'vitest'; +import { getTimeZoneOptionLabel, isAllowedTimeZone, resolveBrowserTimeZone, resolveIanaTimeZone } from './date-time-converter.timezones'; + +describe('date-time-converter timezones', () => { + describe('resolveIanaTimeZone', () => { + test('keeps canonical IANA timezones unchanged', () => { + expect(resolveIanaTimeZone('America/New_York')).toBe('America/New_York'); + }); + + test('keeps a primary timezone when Intl rewrites it to an alias', () => { + expect(resolveIanaTimeZone('Asia/Kolkata')).toBe('Asia/Kolkata'); + expect(resolveIanaTimeZone('Europe/Kyiv')).toBe('Europe/Kyiv'); + }); + + test('rejects aliases that are not selectable IANA options', () => { + expect(resolveIanaTimeZone('Asia/Calcutta')).toBe('Etc/UTC'); + expect(resolveIanaTimeZone('Europe/Kiev')).toBe('Etc/UTC'); + }); + + test('falls back when timezone is invalid', () => { + expect(resolveIanaTimeZone('Not/A_Timezone')).toBe('Etc/UTC'); + expect(resolveIanaTimeZone('Not/A_Timezone', 'America/New_York')).toBe('America/New_York'); + }); + }); + + describe('resolveBrowserTimeZone', () => { + test('canonicalizes browser aliases to selectable IANA zones', () => { + expect(resolveBrowserTimeZone('Asia/Calcutta')).toBe('Asia/Kolkata'); + expect(resolveBrowserTimeZone('Europe/Kiev')).toBe('Europe/Kyiv'); + }); + + test('keeps canonical browser timezones unchanged', () => { + expect(resolveBrowserTimeZone('America/New_York')).toBe('America/New_York'); + }); + }); + + describe('isAllowedTimeZone', () => { + test('accepts only currently selectable timezone values', () => { + expect(isAllowedTimeZone('America/New_York')).toBe(true); + expect(isAllowedTimeZone('Asia/Calcutta')).toBe(false); + expect(isAllowedTimeZone('Not/A_Timezone')).toBe(false); + }); + }); + + describe('getTimeZoneOptionLabel', () => { + test('shows both standard and daylight offsets for DST-aware zones', () => { + expect(getTimeZoneOptionLabel({ + browserTimezone: 'Etc/UTC', + dstOffsetStr: '-04:00', + name: 'America/New_York', + utcOffsetStr: '-05:00', + })).toBe('America/New_York (-05:00/-04:00)'); + }); + + test('marks the browser timezone in the label', () => { + expect(getTimeZoneOptionLabel({ + browserTimezone: 'America/New_York', + dstOffsetStr: '-04:00', + name: 'America/New_York', + utcOffsetStr: '-05:00', + })).toBe('Browser TZ - America/New_York (-05:00/-04:00)'); + }); + }); +}); diff --git a/src/tools/date-time-converter/date-time-converter.timezones.ts b/src/tools/date-time-converter/date-time-converter.timezones.ts new file mode 100644 index 00000000..39f3b8cb --- /dev/null +++ b/src/tools/date-time-converter/date-time-converter.timezones.ts @@ -0,0 +1,100 @@ +import { getAllTimezones, getTimezone } from 'countries-and-timezones'; + +interface TimezoneInfo { + name: string + utcOffsetStr: string + dstOffsetStr: string +} + +const timezones = getAllTimezones() as Record; + +function getCanonicalSelectableTimeZone(timezone?: string) { + const canonicalTimeZone = getTimezone(timezone ?? '')?.aliasOf ?? timezone; + return isAllowedTimeZone(canonicalTimeZone) ? canonicalTimeZone : undefined; +} + +export function isAllowedTimeZone(timezone?: string) { + return typeof timezone === 'string' && !!timezones[timezone]; +} + +export function resolveIanaTimeZone(timezone?: string, fallback = 'Etc/UTC') { + if (!timezone) { + return fallback; + } + + try { + const formatter = new Intl.DateTimeFormat(undefined, { timeZone: timezone }); + const resolvedTimezone = formatter.resolvedOptions().timeZone; + + if (isAllowedTimeZone(timezone)) { + return timezone; + } + + if (isAllowedTimeZone(resolvedTimezone)) { + return resolvedTimezone; + } + + return fallback; + } + catch (_ignored) { + return fallback; + } +} + +export function resolveBrowserTimeZone(timezone?: string, fallback = 'Etc/UTC') { + if (!timezone) { + return fallback; + } + + try { + const formatter = new Intl.DateTimeFormat(undefined, { timeZone: timezone }); + const resolvedTimezone = formatter.resolvedOptions().timeZone; + + for (const candidate of [timezone, resolvedTimezone]) { + const canonicalTimeZone = getCanonicalSelectableTimeZone(candidate); + if (canonicalTimeZone) { + return canonicalTimeZone; + } + } + + return fallback; + } + catch (_ignored) { + return fallback; + } +} + +export function getBrowserTimeZone() { + return resolveBrowserTimeZone(Intl.DateTimeFormat().resolvedOptions().timeZone); +} + +export function getTimeZoneOptionLabel({ + browserTimezone, + dstOffsetStr, + name, + utcOffsetStr, +}: { + browserTimezone: string + dstOffsetStr: string + name: string + utcOffsetStr: string +}) { + const browserPrefix = name === browserTimezone ? 'Browser TZ - ' : ''; + const offsetLabel = utcOffsetStr === dstOffsetStr ? utcOffsetStr : `${utcOffsetStr}/${dstOffsetStr}`; + + return `${browserPrefix}${name} (${offsetLabel})`; +} + +export function getIanaTimeZoneOptions(browserTimezone = getBrowserTimeZone()) { + return Object.values(timezones) + .map(tz => ({ + value: tz.name, + label: getTimeZoneOptionLabel({ + browserTimezone, + dstOffsetStr: tz.dstOffsetStr, + name: tz.name, + utcOffsetStr: tz.utcOffsetStr, + }), + })) + .sort((a, b) => a.label.localeCompare(b.label)); +} diff --git a/src/tools/date-time-converter/date-time-converter.vue b/src/tools/date-time-converter/date-time-converter.vue index b53d0719..bb1e660d 100644 --- a/src/tools/date-time-converter/date-time-converter.vue +++ b/src/tools/date-time-converter/date-time-converter.vue @@ -15,8 +15,8 @@ import { import { ticksFromDate, ticksToDate } from 'tick-time'; import { UTCDate } from '@date-fns/utc'; import { formatInTimeZone } from 'date-fns-tz'; -import { getAllTimezones } from 'countries-and-timezones'; import type { DateFormat, ToDateMapper } from './date-time-converter.types'; +import { getBrowserTimeZone, getIanaTimeZoneOptions, isAllowedTimeZone } from './date-time-converter.timezones'; import { dateToExcelFormat, dateToLDAPTimestamp, @@ -147,21 +147,23 @@ const formatIndex = ref(6); const now = useNow(); // Timezone conversion functionality -const browserTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone; +const browserTimezone = getBrowserTimeZone(); +const defaultStoredTimezone = isAllowedTimeZone(browserTimezone) ? browserTimezone : 'Etc/UTC'; const selectedTimezones = useStorage<{ name: string }[]>( 'date-time-converter:timezones', [], ); -const allTimezones = computed(() => { - return Object.values(getAllTimezones()) - .map(tz => ({ - value: tz.name, - label: `${tz.name} (${tz.utcOffsetStr})`, - })) - .sort((a, b) => a.label.localeCompare(b.label)); -}); +watch(selectedTimezones, (timezones) => { + const filteredTimezones = timezones.filter(({ name }) => isAllowedTimeZone(name)); + + if (filteredTimezones.length !== timezones.length) { + selectedTimezones.value = filteredTimezones; + } +}, { deep: true, immediate: true }); + +const allTimezones = computed(() => getIanaTimeZoneOptions(browserTimezone)); const normalizedDate = computed(() => { if (!inputDate.value) { @@ -249,7 +251,7 @@ function formatDateInTimezone(date: Date | undefined, timezone: string): string