Textual Time Period Converter

3.0.2 · active · verified Tue Apr 21

to-time is a JavaScript/TypeScript utility for parsing and converting textual time periods (e.g., "1 hour", "1y 365d 4h") into various standard time units such as milliseconds, seconds, minutes, hours, days, weeks, and years. The current stable version is 3.0.2, with recent minor and patch releases indicating active development. A key differentiator of to-time is its internal reliance on the `bignumber.js` library to perform arithmetic operations, ensuring high precision and mitigating common floating-point inaccuracies often encountered in time calculations. The package supports dual CommonJS and ESM builds through an `exports` map, providing native compatibility for modern Node.js environments (requiring Node.js 20.19+). It also ships with comprehensive TypeScript types, facilitating robust development. The library offers both a primary parsing function and a suite of static factory methods (`fromMilliseconds`, `fromHours`) for initialization, alongside fluent appender methods (`addMinutes`, `addYears`) for manipulating time frames.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates parsing time strings, using factory methods to create `TimeFrame` instances, chaining appender methods, and retrieving values in various units, including human-readable formats. It highlights practical usage for setting time-based operations like `setTimeout`.

import toTime from 'to-time';

// Example 1: Parsing a textual time period and getting total days
// Converts "1 year and 6 months" to total days, demonstrating precision.
const daysInYearAndHalf = toTime('1 Year 6 Months').days();
console.log(`Days in 1 year and 6 months: ${daysInYearAndHalf}`);
// Expected output: Days in 1 year and 6 months: 547.5

// Example 2: Using factory methods for clearer time intervals in milliseconds
const twelveHoursInMs = toTime.fromHours(12).ms();
console.log(`12 hours in milliseconds: ${twelveHoursInMs}`);
// Expected output: 12 hours in milliseconds: 43200000

// Using it with setInterval/setTimeout for clear, human-readable delays.
// Simulate an action after 1.5 hours without blocking.
console.log('Simulating an action scheduled after 1.5 hours...');
setTimeout(() => {
  console.log('Action performed after 1.5 hours.');
}, toTime.fromHours(1.5).ms());

// Example 3: Combining parsing, appending units, and humanizing the output
const combinedTime = toTime('2 days 3 hours').addMinutes(90).humanize();
console.log(`Combined time (2 days, 3 hours + 90 minutes) humanized: ${combinedTime}`);
// Expected output: Combined time (2 days, 3 hours + 90 minutes) humanized: 2 days, 4 hours, 30 minutes

view raw JSON →