npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@reasonable-stack/datetime

v0.3.0

Published

Some reasonably good datetime primitives.

Readme

@reasonable-stack/datetime

Some reasonably good datetime primitives for TypeScript.

JavaScript's native Date is a single type doing the job of several: it is an instant, a calendar date and a wall-clock time all at once, it silently accepts invalid input, it counts months from zero and it is mutable.

This library gives each concept its own small, immutable type:

| type | represents | example | | :--------- | :------------------------------------------- | :------------------------- | | Date | a calendar date, no time and no timezone | 2024-02-29 | | Time | a wall-clock time, no date and no timezone | 13:45:00.000 | | DateTime | an instant, in UTC | 2024-02-29T13:45:00.000Z | | Duration | an exact length of time, in days and smaller | P1DT12H |

It is meant to be simpler than Temporal: no calendars other than ISO 8601, no IANA timezones, no daylight saving time, no months or years in durations.

Installation

npm install @reasonable-stack/datetime

Quick start

import * as r from 'reasonable-datetime';

const due = r.Date.parse('2024-02-28').add(r.days(2));
due.toISOString(); // => '2024-03-01'

const meeting = r.DateTime.parse('2024-02-29T13:45-03:00');
meeting.add(r.minutes(90)).toISOString(); // => '2024-02-29T15:15:00.000-03:00'

const lunch = r.Time.parse('12:00');
lunch.diff(r.Time.parse('13:30')).toISOString(); // => 'PT1H30M'

JSON.stringify({ due, meeting }); // => '{"due":"2024-03-01","meeting":"2024-02-29T13:45:00.000-03:00"}'

Tip: this library exports a class named Date, which would shadow the native Date if imported by name. That is why every example here uses a namespace import, import * as r from 'reasonable-datetime'.

Common behavior

Every type follows the same rules:

  • Construction. new takes the fields; the static parse reads an ISO string (or, for DateTime, milliseconds since the Unix epoch).
  • Immutable. Fields are read-only and every operation returns a new instance.
  • Strict. Malformed strings and out-of-range fields throw a RangeError instead of rolling over — 2023-02-29, 24:00 and 13:60 are all errors.
  • Months start at 1. January is 1, December is 12.
  • Years range from 0 to 9999, so ISO strings always have a 4-digit year. Years 0 to 99 are taken literally (0050 is year 50, not 1950).
  • Serializes as ISO 8601. toISOString(), toString() and toJSON() return the same string, so instances work in template literals and JSON.stringify.
  • Comparison returns -1, 0 or 1, so compare works as an Array.prototype.sort comparator.
  • diff goes from this to other. a.diff(b) is b − a, so a.add(a.diff(b)) is always b.
  • Collections. Each type has static sort, min and max, and sort is also available as the r.sort helper. sort returns a new array (the input is left untouched); min and max throw a RangeError on an empty array.
  • Type guards. Each type has a static is(value), which narrows an unknown value to that type.
const dates = [r.Date.parse('2024-03-01'), r.Date.parse('2023-12-31')];

r.sort(dates).map(String);    // => ['2023-12-31', '2024-03-01']
r.Date.min(dates).toString(); // => '2023-12-31'

r.Date.is(dates[0]); // => true
r.Time.is(dates[0]); // => false

Helpers

The most common static methods are also exported as plain functions, for shorter call sites:

| helper | same as | | :------------------ | :----------------------------------------------------------------------------- | | r.nowUTC() | r.DateTime.nowUTC() | | r.todayUTC() | r.Date.todayUTC() | | r.days(n) | r.Duration.days(n) | | r.hours(n) | r.Duration.hours(n) | | r.minutes(n) | r.Duration.minutes(n) | | r.seconds(n) | r.Duration.seconds(n) | | r.milliseconds(n) | r.Duration.milliseconds(n) | | r.sort(items) | r.Date.sort(items), r.Time.sort(items), … for whichever type items holds | | r.compare(a, b) | a.compare(b) |

import * as r from 'reasonable-datetime';

r.Date.parse('2024-02-28').add(r.days(2)).toISOString(); // => '2024-03-01'

r.sort([r.hours(3), r.minutes(90)]).map(String); // => ['PT1H30M', 'PT3H']
r.compare(r.days(2), r.hours(36));               // => 1

sort and compare work with any of the four types, but in TypeScript all values must be of the same type — mixing, say, a Date and a Time is a compile-time error, since they can't be meaningfully compared.

Since compare returns the -1, 0 or 1 that Array.prototype.sort expects, it can be used in a custom sort function — for example, to sort records by one of their fields:

const events = [
  { name: 'launch', at: r.Date.parse('2024-03-01') },
  { name: 'kickoff', at: r.Date.parse('2023-12-31') },
];

events.toSorted((a, b) => a.at.compare(b.at)).map((e) => e.name);
// => ['kickoff', 'launch']

events.toSorted((a, b) => b.at.compare(a.at)).map((e) => e.name);
// => ['launch', 'kickoff'] (descending)

Date

A calendar date: a year, a month and a day. No time, no timezone.

r.Date.parse('2024-02-29');                    // from an ISO date (YYYY-MM-DD)
new r.Date({ year: 2024, month: 2, day: 29 }); // from its fields
r.todayUTC();                                  // the current date in UTC

| field | range | | :------ | :-------- | | year | 0..9999 | | month | 1..12 | | day | 1..31 |

| method | returns | description | | :------------------------------- | :------------- | :------------------------------------------- | | add(duration) | Date | moves forward by a whole number of days | | sub(duration) | Date | moves backward by a whole number of days | | diff(other) | Duration | the number of days from this date to other | | compare(other) | -1 \| 0 \| 1 | compares dates | | beginningOf('year' \| 'month') | Date | the first day of the year or month | | endOf('year' \| 'month') | Date | the last day of the year or month | | toISOString() | string | e.g. '2024-02-29' |

Dates only move in whole days. Adding a duration with leftover hours, minutes, seconds or milliseconds throws a RangeError:

const date = r.Date.parse('2024-01-01');

date.add(r.hours(48)).toISOString(); // => '2024-01-03'
date.add(r.hours(5));                // throws RangeError

r.Date.parse('2024-02-14').endOf('month').toISOString(); // => '2024-02-29'

Time

A wall-clock time, with millisecond precision. No date, no timezone.

r.Time.parse('13:45');                // HH:MM
r.Time.parse('13:45:30');             // HH:MM:SS
r.Time.parse('13:45:30.5');           // HH:MM:SS.s, up to 3 fraction digits
new r.Time({ hour: 13, minute: 45 }); // second and millisecond default to 0

| field | range | | :------------ | :------- | | hour | 0..23 | | minute | 0..59 | | second | 0..59 | | millisecond | 0..999 |

| method | returns | description | | :--------------- | :------------- | :------------------------------------------- | | add(duration) | Time | moves forward, wrapping around midnight | | sub(duration) | Time | moves backward, wrapping around midnight | | diff(other) | Duration | the time from this time to other | | compare(other) | -1 \| 0 \| 1 | compares times | | toISOString() | string | always HH:MM:SS.sss, e.g. '13:45:00.000' |

Times wrap around midnight, so adding whole days leaves a time unchanged:

r.Time.parse('23:00').add(r.hours(2)).toISOString(); // => '01:00:00.000'
r.Time.parse('10:00').add(r.days(3)).toISOString();  // => '10:00:00.000'

DateTime

An instant in time, in UTC. The date and time fields are the wall-clock reading in UTC.

r.DateTime.parse('2024-02-29T13:45:30.5-03:00'); // from an ISO date-time, converted to UTC
r.DateTime.parse(1709225130500);                 // from milliseconds since the Unix epoch
new r.DateTime({                                 // from its fields, in UTC
  year: 2024, month: 2, day: 29,
  hour: 13, minute: 45,                          // time fields default to 0
});
r.nowUTC();                                      // the current instant

ISO strings must include an offset, either Z or ±HH:MM. A date-time without one is ambiguous, so r.DateTime.parse('2024-02-29T13:45') throws a RangeError. The offset is only used to find the instant, and is not kept:

r.DateTime.parse('2024-02-29T13:45-03:00').toISOString(); // => '2024-02-29T16:45:00.000Z'

| field | range | | :------------ | :---------------------------------------- | | year | 0..9999 | | month | 1..12 | | day | 1..31 | | hour | 0..23 | | minute | 0..59 | | second | 0..59 | | millisecond | 0..999 | | epoch | milliseconds since 1970-01-01T00:00:00Z |

| method | returns | description | | :---------------------------------------- | :------------- | :------------------------------------------------ | | add(duration) | DateTime | moves forward | | sub(duration) | DateTime | moves backward | | diff(other) | Duration | the exact time from this instant to other | | compare(other) | -1 \| 0 \| 1 | compares instants | | beginningOf('year' \| 'month' \| 'day') | DateTime | the first millisecond of the unit | | endOf('year' \| 'month' \| 'day') | DateTime | the last millisecond of the unit (23:59:59.999) | | date() | Date | the date in UTC | | time() | Time | the time in UTC | | toNativeDate() | native Date | the same instant as a native Date | | toISOString() | string | always in UTC, e.g. '2024-02-29T13:45:00.000Z' |

Two ISO strings for the same instant parse to equal date-times, whatever their offsets:

const a = r.DateTime.parse('2024-01-01T12:00+02:00');
const b = r.DateTime.parse('2024-01-01T10:00Z');

r.compare(a, b);         // => 0
a.diff(b).toISOString(); // => 'PT0S'

Because date-times are always in UTC, a day is always exactly 24 hours — there is no daylight saving time to account for. The date and time are read in UTC, which may not be the date and time of the parsed string:

const night = r.DateTime.parse('2024-02-29T23:30-03:00');

night.date().toISOString();         // => '2024-03-01'
night.time().toISOString();         // => '02:30:00.000'
night.toNativeDate().toISOString(); // => '2024-03-01T02:30:00.000Z'

Duration

An exact length of time, positive or negative. Durations have no months or years, since those have no fixed length, so any two durations can be compared.

new r.Duration({ days: 1, hours: 12 }); // any combination of fields, all optional
r.days(1);
r.hours(1.5);                           // fractions are fine: 1 hour and 30 minutes
r.minutes(5);
r.seconds(30);
r.milliseconds(250);

Fields are normalized, so every duration has a single representation:

const duration = new r.Duration({ hours: 36 });

duration.days;  // => 1
duration.hours; // => 12

| field | range | | :------------- | :-------- | | days | any | | hours | ±0..23 | | minutes | ±0..59 | | seconds | ±0..59 | | milliseconds | ±0..999 |

A negative duration has every field negative: -36 hours is { days: -1, hours: -12 }. The total is rounded to whole milliseconds, and non-finite values (NaN, Infinity) throw a RangeError.

| method | returns | description | | :--------------- | :------------- | :------------------------------------- | | add(duration) | Duration | the sum | | sub(duration) | Duration | the difference, this − duration | | diff(other) | Duration | the difference, other − this | | compare(other) | -1 \| 0 \| 1 | compares total lengths | | toISOString() | string | an ISO 8601 duration, e.g. 'P1DT12H' |

r.compare(r.hours(36), r.days(2)); // => -1

new r.Duration({}).toISOString();    // => 'PT0S'
r.milliseconds(-1250).toISOString(); // => '-PT1.25S'

License

MIT