Timespan is a lightweight, powerful library for working with time intervals in JavaScript and TypeScript. Whether you're measuring durations, formatting human-readable strings, or converting between time units — Timespan makes it effortless.
Install via your preferred package manager:
$ npm install @undercroft/timespan
Or load it from one of the available CDNs:
CDN | Link | Copy |
---|---|---|
jsDelivr | https://cdn.jsdelivr.net/npm/@undercroft/timespan/dist/index.umd.js | |
unpkg | https://unpkg.com/@undercroft/timespan/dist/index.umd.js | |
Skypack | https://cdn.skypack.dev/@undercroft/timespan | |
esm.sh | https://esm.sh/@undercroft/timespan | |
jspm | https://jspm.dev/@undercroft/timespan | |
esm.run | https://esm.run/@undercroft/timespan |
import { Timespan } from "@undercroft/timespan";
const span = new Timespan(new Date(), new Date());
console.log(span.toMilliseconds());
<script src="https://cdn.jsdelivr.net/npm/@undercroft/timespan/dist/index.umd.js"></script>
<script>
const span = new window.Timespan(new Date(), new Date());
console.log(span.toMilliseconds());
</script>
You can create a Timespan using either a string input or start/end dates.
const input = "3d 5h 30m";
const span = Timespan.fromString(input);
console.log(span.toString()); // "3d 5h 30m"
console.log(span.toHours()); // 77.5
const start = new Date("2023-01-01");
const end = new Date("2023-01-15");
const span = new Timespan(start, end);
console.log(span.toDays()); // 14
const span = new Timespan(new Date("2023-01-01"), new Date("2023-01-15"));
console.log(span.start); // 2023-01-01T00:00:00.000Z
console.log(span.end); // 2023-01-15T00:00:00.000Z
console.log(span.toTimeframe()); // { weeks: 2, days: 0, ... }
console.log(span.toMilliseconds()); // 1209600000
const span = new Timespan(new Date("2023-01-01"), new Date("2023-01-15"));
console.log(span.toHours()); // 336
console.log(span.toWeeks()); // 2
console.log(span.toMonths()); // 0
console.log(span.toYears()); // 0
Timespan.fromMilliseconds(5000);
Timespan.fromSeconds(120);
Timespan.fromMinutes(60);
Timespan.fromHours(24);
Timespan.fromDays(7);
Timespan.fromWeeks(4);
Timespan.fromMonths(6);
Timespan.fromYears(2);
const span1 = Timespan.fromHours(12);
const span2 = Timespan.fromDays(2);
const added = span1.add(span2);
const subtracted = span2.subtract(span1);
const isEqual = span1.equals(span2);
const comparison = span1.compareTo(span2); // -1, 0, or 1
Contributions are welcome! Feel free to open issues or submit pull requests on the GitHub repository.
Timespan is open source under the MIT License.