Skip to content

Main content

Random Time Generator Source Code

Browse the implementation files for Random Time Generator.
tool.ts typescript
import { calculateRandomTime as calculatePortableRandomTime } from '@tool.io/tools/random/time';
import type { RandomSource } from '@tool.io/tools/random/number';
import { validateChoice } from '../../../tool-runtime/validateChoice';

const FORMATS = ['24-hour', '12-hour'] as const;
const PRECISIONS = ['minutes', 'seconds'] as const;

export type RandomTimeValue = {
	secondsSinceMidnight: number;
	hours: number;
	minutes: number;
	seconds: number;
};

export const calculateRandomTime = (
	random: RandomSource = Math.random
): RandomTimeValue | null => {
	const result = calculatePortableRandomTime(
		'24-hour',
		'seconds',
		random
	);
	if (result === null) return null;
	const { hours, minutes, seconds, secondsSinceMidnight } =
		result;
	return { hours, minutes, seconds, secondsSinceMidnight };
};

export const randomTime = (
	formatInput: unknown,
	precisionInput: unknown,
	random: RandomSource = Math.random
): string => {
	const format = validateChoice(formatInput, FORMATS);
	const precision = validateChoice(precisionInput, PRECISIONS);

	if (format === null || precision === null) return '';

	return (
		calculatePortableRandomTime(format, precision, random)
			?.text ?? ''
	);
};

export const Tool: TypeTool = {
	name: 'Random Time Generator',
	slug: 'random/time',
	intro:
		'Generate a random clock time in 12-hour or 24-hour format.',
	tool: randomTime,
	i: [
		{
			example: '24-hour',
			label: 'Clock format',
			placeholder: 'Clock format',
			type: 'select',
			value: '24-hour',
			options: [
				{ value: '24-hour', text: '24-hour', selected: true },
				{ value: '12-hour', text: '12-hour' }
			]
		},
		{
			example: 'minutes',
			label: 'Precision',
			placeholder: 'Precision',
			type: 'select',
			value: 'minutes',
			options: [
				{ value: 'minutes', text: 'Minutes', selected: true },
				{ value: 'seconds', text: 'Seconds' }
			]
		}
	],
	o: [
		{
			example: '18:00',
			label: 'Random time',
			placeholder: 'Random time',
			render: 'textarea',
			type: 'text'
		}
	],
	rerunnable: true,
	alternative: [
		{ title: 'Random Date', url: '/random/date' },
		{ title: 'Random Timestamp', url: '/random/timestamp' }
	],
	cite: [
		{
			title: '12-hour clock - Wikipedia',
			url: 'https://en.wikipedia.org/wiki/12-hour_clock'
		},
		{
			title: '24-hour clock - Wikipedia',
			url: 'https://en.wikipedia.org/wiki/24-hour_clock'
		}
	]
};

export default Tool;

Description

Browse the implementation files for Random Time Generator.

References

  1. Tool.io on GitHub
  2. Tool.io TypeScript tools library

Similar or alternative tools