Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@undercroft/timespan

mikejg101390MIT1.1.0TypeScript support: included

When dealing with time durations or intervals in JavaScript, it's often useful to have a reliable way to represent and manipulate them. The Timespan class provides a convenient and powerful solution for working with timespans in JavaScript.

timespan, duration, date, time, datetime, timeframe, interval, javascript, typescript, time parser, time formatter, human-readable, date math, date utilities, date calculation, library, esm, umd, node, browser, undercroft

readme

Timespan — Intuitive Time Interval Calculations in JavaScript

When dealing with time durations or intervals in JavaScript, it's often useful to have a reliable way to represent and manipulate them. The Timespan class provides a convenient and powerful solution for working with timespans in JavaScript.

Works in Typescript too!

Build Status Issues Status Pull Request Status NPM Version Status License Status Bundle Size Install Size Coverage Status Known Vulnerabilities

UMD Support

Starting with version 1.1.0, you can use Timespan directly in the browser via the UMD build. All public methods are supported.

Distribution & Compatibility

  • Small bundle footprint (<4kB brotli-compressed)
  • Works in Node.js, modern browsers, and bundlers

Test Coverage & CI

  • Full unit test coverage with Jest
  • Automatically tested on Ubuntu and Windows
  • Bundle size tracked via Size Limit
  • Code coverage reported via Codecov

Breaking Changes (as of 1.1.0)

  • Removed internal module access — All usage must go through the public Timespan export
  • Internal validation and type guards added
  • Removed legacy and deprecated utility modules

Installation

Usage in NodeJS

npm install @undercroft/timespan

Then use it like this.

import { Timespan } from '@undercroft/timespan';

Usage in Browser


<script src="https://cdn.jsdelivr.net/npm/@undercroft/timespan/dist/index.umd.js"></script>

Then use it like this.


<script>
  const span = new window.Timespan(new Date(), new Date());
  console.log(span.toMilliseconds());
</script>

Creating Timespans

To create a Timespan object, we can use the fromString method or directly instantiate it with start and end dates.

Creating a Timespan from a String

import { Timespan } from '@undercroft/timespan';

const input = '3d 5h 30m'; // Example input string representing a timespan
const timespan = Timespan.fromString(input);

console.log(timespan.toString()); // Output: '3d 5h 30m'
console.log(timespan.toHours()); // Output: 77.5

In the example above, we create a Timespan object from an input string using the fromString method. The input string specifies a timespan of 3 days, 5 hours, and 30 minutes. We then output the string representation of the timespan using toString() and calculate the total duration in hours using toHours().

Creating a Timespan with Start and End Dates

import { Timespan } from '@undercroft/timespan';

const start = new Date('2023-01-01');
const end = new Date('2023-01-15');
const timespan = new Timespan(start, end);

console.log(timespan.toDays()); // Output: 14

In this example, we create a Timespan object by providing the start and end dates directly. We then calculate the total duration in days using toDays().

Retrieving Timespan Information

The Timespan class provides various methods to retrieve information about a timespan.

import { Timespan } from '@undercroft/timespan';

const start = new Date('2023-01-01');
const end = new Date('2023-01-15');
const timespan = new Timespan(start, end);

// Output: 2023-01-01T00:00:00.000Z
console.log(timespan.start);

// Output: 2023-01-15T00:00:00.000Z
console.log(timespan.end);

// Output: { years: 0, months: 0, weeks: 2, days: 0, hours: 0, minutes: 0, seconds: 0, milliseconds: 0 }
console.log(timespan.toTimeframe());

// Output: 1209600000
console.log(timespan.toMilliseconds());

In the example above, we retrieve the start and end dates of the timespan using the start and end properties. We also obtain the timespan represented as a TimeFrame object using toTimeframe(), which provides the individual components of the timespan such as years, months, weeks, days, hours, minutes, seconds, and milliseconds. Lastly, we calculate the total duration in milliseconds using toMilliseconds().

Converting Timespans

The Timespan class provides convenient methods to convert a timespan to different units of time.

import { Timespan } from '@undercroft/timespan';

const start = new Date('2023-01-01');
const end = new Date('2023-01-15');
const timespan = new Timespan(start, end);

console.log(timespan.toHours()); // Output: 336
console.log(timespan.toWeeks()); // Output: 2
console.log(timespan.toMonths()); // Output: 0
console.log(timespan.toYears()); // Output: 0

In this example, we convert the timespan to various units such as hours, weeks, months, and years using the respective conversion methods.

More Examples of Creating TimeSpans

You can create a Timespan object using the static methods provided by the class. Here are the available methods:

Timespan.fromMilliseconds(milliseconds: number, startDate?: Date): Timespan Creates a Timespan object from a specified number of milliseconds.

import { Timespan } from '@undercroft/timespan';

const timespan = Timespan.fromMilliseconds(5000);
Timespan.fromSeconds(seconds, startDate);

Creates a Timespan object from a specified number of seconds.

import { Timespan } from '@undercroft/timespan';

const timespan = Timespan.fromSeconds(120);
Timespan.fromMinutes(minutes, startDate);

Creates a Timespan object from a specified number of minutes.

import { Timespan } from '@undercroft/timespan';

const timespan = Timespan.fromMinutes(60);
Timespan.fromHours(hours, startDate);

Creates a Timespan object from a specified number of hours.

import { Timespan } from '@undercroft/timespan';

const timespan = Timespan.fromHours(24);
Timespan.fromDays(days, startDate);

Creates a Timespan object from a specified number of days.

import { Timespan } from '@undercroft/timespan';

const timespan = Timespan.fromDays(7);
Timespan.fromWeeks(weeks, startDate);

Creates a Timespan object from a specified number of weeks.

import { Timespan } from '@undercroft/timespan';

const timespan = Timespan.fromWeeks(4);
Timespan.fromMonths(months, startDate);

Creates a Timespan object from a specified number of months.

import { Timespan } from '@undercroft/timespan';

const timespan = Timespan.fromMonths(6);
Timespan.fromYears(years, startDate);

Creates a Timespan object from a specified number of years.

import { Timespan } from '@undercroft/timespan';

const timespan = Timespan.fromYears(2);

Performing Calculations and Comparisons Once you have a Timespan object, you can perform various calculations and comparisons using the provided methods. Here are some examples:

import { Timespan } from '@undercroft/timespan';

const timespan1 = Timespan.fromHours(12);
const timespan2 = Timespan.fromDays(2);

const addedTimespan = timespan1.add(timespan2);
const subtractedTimespan = timespan2.subtract(timespan1);
const areEqual = timespan1.equals(timespan2);
const comparisonResult = timespan1.compareTo(timespan2);

Please refer to the API documentation, or the source code for more details on the available methods and their usage.

Contributing

Contributions to the Timespan class are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request on the GitHub repository.

License

The Timespan class is licensed under the MIT License. See the LICENSE file for more information.

changelog

Changelog

All notable changes to this project will be documented in this file.

[1.1.0] – 2025-04-13

⚠ BREAKING CHANGE:
Internal modules have been fully restructured. If you're importing from internal paths, update your imports to use the main public interface. Direct deep imports are no longer supported.

Added

  • UMD Web Build: The library can now be used directly in the browser via a CDN like jsDelivr. A window.Timespan global is now available for browser usage.
  • Static Web Test Page: Added web-test.html to validate UMD builds and expose all public methods.
  • Size Monitoring: Size tracking with Size Limit is now integrated into CI for bundle size awareness.
  • Code Coverage Reporting: Integration with Codecov for unit test coverage tracking.
  • Jest JUnit Reporting: Support added for CI-friendly test result outputs in reports/junit.xml.

Changed

  • Timespan.toString(startDate) now accepts an optional base date to anchor formatting.
  • The internal unit conversion system was fully modularized:
    • Constants, formatting, and calculations now live in separate utility files.
    • Assertion functions and type guards improve runtime validation.
  • Build system now uses Rollup for UMD and tsup for ESM/CJS builds.
  • Node.js version requirements updated in CI to test against latest versions.
  • npm run clean and build scripts improved for cross-platform compatibility.

Removed

  • Legacy utility and calculation files.
  • Typedoc generation (temporarily) due to CI inconsistencies.

Fixed

  • Resolved a bug that caused incorrect day calculations in some scenarios.
  • Timezone-related parsing issues fixed.
  • Fixed issues with dependency audits targeting dev-only modules.

[1.0.5] – April 11, 2025

  • Public interface simplified: consumers now only import from the root module.
  • Moved internal constants out of Timespan and into dedicated files.
  • Timespan.fromString() now accepts an optional start date for relative parsing.
  • Line-ending formatting issues resolved across platforms.

[1.0.4] – May 27, 2023

  • Bugfix: incorrect duration calculations involving days and timezones.
  • Internal structure improvements and additional unit tests.
  • Added standard community documents (e.g., Code of Conduct, license metadata).
  • Migrated all internal tooling to TypeScript.

[1.0.3] – May 27, 2023

  • Feature: improved accuracy for duration breakdown and parsing logic.

[1.0.2] – May 27, 2023

  • Documentation: updated usage examples in README to reflect current API.

[1.0.1] – May 27, 2023

  • Docs: added project badges and refined installation instructions.

[1.0.0] – May 27, 2023

  • Initial release of the Timespan utility.
  • Included CLI tools, parsing, formatting, and duration breakdown support.