mirror of
https://github.com/sharevb/it-tools.git
synced 2026-12-04 18:35:09 +03:00
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.
This commit is contained in:
1 parent
ba1bea3944
commit
03bb1e5711
4 files changed
+226
-13
No files matched your search
@@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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)');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import { getAllTimezones, getTimezone } from 'countries-and-timezones';
|
||||
|
||||
interface TimezoneInfo {
|
||||
name: string
|
||||
utcOffsetStr: string
|
||||
dstOffsetStr: string
|
||||
}
|
||||
|
||||
const timezones = getAllTimezones() as Record<string, TimezoneInfo>;
|
||||
|
||||
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));
|
||||
}
|
||||
@@ -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
|
||||
<n-dynamic-input
|
||||
v-model:value="selectedTimezones"
|
||||
show-sort-button
|
||||
:on-create="() => ({ name: browserTimezone })"
|
||||
:on-create="() => ({ name: defaultStoredTimezone })"
|
||||
>
|
||||
<template #default="{ value }">
|
||||
<div w-full flex items-center gap-2>
|
||||
@@ -278,7 +280,7 @@ function formatDateInTimezone(date: Date | undefined, timezone: string): string
|
||||
<div v-else mb-4 mt-4>
|
||||
<c-button
|
||||
size="small"
|
||||
@click="selectedTimezones.push({ name: browserTimezone })"
|
||||
@click="selectedTimezones.push({ name: defaultStoredTimezone })"
|
||||
>
|
||||
{{ t('tools.date-time-converter.texts.button-add-timezone') }}
|
||||
</c-button>
|
||||
|
||||
Reference in new issue
Block a user