@papack/time
v1.0.1
Published
timestamp calculation and formatting utilities
Readme
@papack/time
Utility module for working with timestamps (milliseconds), durations, and formatting.
- All values are milliseconds (
Date.now()compatible) - Locale must always be passed explicitly
Import
import {
// formatting
formatRelative,
formatDuration,
formatDate,
// time utils
now,
since,
until,
add,
sub,
// duration builders
seconds,
minutes,
hours,
days,
// async
sleep,
// constants
SECOND,
MINUTE,
HOUR,
DAY,
MONTH,
YEAR,
} from "@papack/time";Relative time
Formats a timestamp relative to now.
const ts = now() - 5 * MINUTE;
formatRelative(ts, "en");
// "5 minutes ago"
formatRelative(now() + 2 * HOUR, "en");
// "in 2 hours"Behavior:
- direction is automatic (past/future)
- small deltas (<1s) are treated as “now” to avoid flicker
- units: seconds -> years (month/year are approximations)
Duration
Formats a duration (not a timestamp).
formatDuration(2 * HOUR + 30 * MINUTE, "en");
// "2 hours, 30 minutes" (if Intl.DurationFormat is available)
// or "2h 30m" (fallback)
formatDuration(1 * DAY + 2 * HOUR, "en");
// "1 day, 2 hours"
formatDuration(0, "en");
// "0 minutes" or "0m"Notes:
- input is treated as absolute (
Math.abs) - prefers
Intl.DurationFormat - falls back to compact format if not available
Date formatting
Wrapper around Intl.DateTimeFormat.
formatDate(now(), "en", {
dateStyle: "medium",
timeStyle: "short",
});
// "May 4, 2026, 14:30"Time helpers
Current time
now(); // number (ms)Differences
const start = now() - 5 * MINUTE;
since(start); // elapsed ms
until(now() + 10 * MINUTE); // remaining msArithmetic
const start = now();
add(start, 5 * MINUTE); // timestamp + duration
sub(start, 2 * HOUR); // timestamp - durationDuration builders
seconds(5); // 5000
minutes(2); // 120000
hours(1); // 3600000
days(3); // 259200000Used for readability:
add(now(), minutes(5));
await sleep(seconds(2));Sleep
await sleep(1000);
await sleep(seconds(1));Constants
All values are milliseconds.
5 * MINUTE;
2 * HOUR + 30 * MINUTE;Available:
SECONDMINUTEHOURDAYMONTH(~30 days, approximation)YEAR(~365 days, approximation)
Typical usage
const expiresAt = add(now(), minutes(5));
formatRelative(expiresAt, locale);
// "in 5 minutes"
const elapsed = since(start);
// number (ms)
await sleep(seconds(1));Notes
- no timezone handling beyond
Intl - month/year are approximations
- output depends on runtime
Intlsupport - all functions are pure (except
sleep)
