Bookmark this: tool.io/clock/source-code
Clock Source Code
Browse the implementation files for Clock.tool.ts typescript
// Tool: Clock
type ClockFormat = '12-hour' | '24-hour';
const FORMATS: ClockFormat[] = ['24-hour', '12-hour'];
const parseDate = (input: unknown): Date | null => {
if (input === undefined) return new Date();
const date = input instanceof Date ? input : new Date(input as string | number);
return Number.isNaN(date.getTime()) ? null : date;
};
const getPart = (
parts: Intl.DateTimeFormatPart[],
type: Intl.DateTimeFormatPartTypes
): string => parts.find((part) => part.type === type)?.value ?? '';
export const clock = (
timeZoneInput: unknown,
formatInput: unknown,
dateInput?: unknown
): string => {
if (
typeof timeZoneInput !== 'string' ||
!FORMATS.includes(formatInput as ClockFormat)
) {
return '';
}
const date = parseDate(dateInput);
if (date === null) return '';
try {
const options: Intl.DateTimeFormatOptions = {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hourCycle: formatInput === '24-hour' ? 'h23' : 'h12'
};
if (timeZoneInput !== 'local') options.timeZone = timeZoneInput;
const parts = new Intl.DateTimeFormat('en-US', options).formatToParts(date);
const time = `${getPart(parts, 'hour')}:${getPart(parts, 'minute')}:${getPart(parts, 'second')}`;
return formatInput === '12-hour'
? `${time} ${getPart(parts, 'dayPeriod')}`
: time;
} catch {
return '';
}
};
export const Tool: TypeTool = {
name: 'Clock',
slug: 'clock',
intro: 'Show the current time in a selected time zone.',
tool: clock,
i: [
{
example: 'local',
label: 'Time Zone',
placeholder: 'Select a time zone',
type: 'select',
value: 'local',
options: [
{ value: 'local', text: 'Local time', selected: true },
{ value: 'UTC', text: 'UTC' },
{ value: 'America/Los_Angeles', text: 'Los Angeles' },
{ value: 'America/New_York', text: 'New York' },
{ value: 'Europe/London', text: 'London' },
{ value: 'Europe/Berlin', text: 'Berlin' },
{ value: 'Asia/Kolkata', text: 'New Delhi' },
{ value: 'Asia/Singapore', text: 'Singapore' },
{ value: 'Asia/Tokyo', text: 'Tokyo' },
{ value: 'Australia/Sydney', text: 'Sydney' }
]
},
{
example: '24-hour',
label: 'Clock Format',
placeholder: 'Select a clock format',
type: 'select',
value: '24-hour',
options: [
{ value: '24-hour', text: '24-hour', selected: true },
{ value: '12-hour', text: '12-hour' }
]
}
],
o: [
{
example: '18:00:00',
label: 'Current Time',
placeholder: 'Current time will appear here...',
type: 'text'
}
],
rerunnable: true,
alternative: [{ title: 'World Clock', url: '/world-clock' }],
cite: [
{
title: 'Time zone - Wikipedia',
url: 'https://en.wikipedia.org/wiki/Time_zone'
}
]
};
export default Tool;
Description
Browse the implementation files for Clock.