Overview
APITime and duration manipulation
Installation
- yarn
- pnpm
- npm
yarn add @w5s/time
pnpm add @w5s/time
npm install @w5s/time
Motivation
The @w5s/time package provides type-safe utilities for working with time and durations. It offers:
- Time: Represents a point in time (timestamp in milliseconds)
- TimeDuration: Represents a duration (amount of milliseconds)
Both types are branded numbers, providing type safety while maintaining full compatibility with JavaScript's numeric operations.
Quick Start
import { Task } from '@w5s/task';
import { Time, TimeDuration } from '@w5s/time';
// Get current time
const currentTimeTask = Time.now();
const result = await Task.run(currentTimeTask);
// Create a duration
const twoMinutes = TimeDuration({ minutes: 2 });
const oneHour = TimeDuration({ hours: 1 });
// Add duration to time
const futureTime = Time['+'](result.value, twoMinutes);
// Compare times
Time['<'](result.value, futureTime); // true
Key Concepts
Time
Time represents a specific point in time as milliseconds since Unix epoch (same as Date.now()):
import { Time } from '@w5s/time';
// Create from timestamp
const time = Time.of(1609459200000);
// Create from date components
const dateTime = Time.from({
year: 2021,
month: 1,
day: 1,
hour: 0,
minute: 0,
second: 0,
});
// Parse from ISO string
const parsed = Time.parse('2021-01-01T00:00:00.000Z');
TimeDuration
TimeDuration represents an amount of time in milliseconds:
import { TimeDuration } from '@w5s/time';
// Create from components
const duration = TimeDuration({
hours: 2,
minutes: 30,
seconds: 15,
});
// Create from raw milliseconds
const rawDuration = TimeDuration.of(9015000);
// Convert to different units
TimeDuration.toHours(duration); // 2.5...
TimeDuration.toMinutes(duration); // 150.25
TimeDuration.toSeconds(duration); // 9015