datetime.delta
v0.1.0 latestCompute the time difference between two timestamps in milliseconds or seconds per ISO 8601.
Compute the time difference between two timestamps in milliseconds or seconds per ISO 8601.
Signature
function delta(a: Date | number, b: Date | number, opt?: DeltaOptions): number
Type Definitions:
DeltaOptions— interface
Problem
Calculating time differences requires handling both Date objects and numeric timestamps, validating invalid dates and non-finite numbers, and converting between milliseconds and seconds. Ad-hoc getTime() subtraction lacks validation and unit conversion.
How It Works
Accepts Date objects or numeric millisecond timestamps interchangeably. Returns a - b in milliseconds by default, or seconds with unit: 's'. Pure arithmetic — no Intl dependency.
Boundaries
- Number inputs are always treated as milliseconds (epoch ms).
- Invalid Date objects → TypeError.
- Non-finite numbers (NaN, Infinity) → TypeError.
- Non-Date/non-number arguments → TypeError.
- Result is signed (a - b) unless abs: true.
Replaces
Common boilerplate this function replaces:
dateA.getTime() - dateB.getTime()
Examples
datetime.delta(new Date("2024-01-01T01:00:00Z"), new Date("2024-01-01T00:00:00Z")); // 3600000
datetime.delta(5000, 0, { unit: "s" }); // 5
datetime.delta(0, 1000, { abs: true }); // 1000
datetime.delta(0, 1000); // -1000
Standards
Caveats
- No Intl dependency — uses pure arithmetic on epoch milliseconds.
- Number inputs are always milliseconds, not seconds. Divide by 1000 if your source is Unix seconds.
FAQ
How to calculate time difference in JavaScript?
datetime.delta(dateA, dateB) returns the difference in milliseconds. Use { unit: 's' } for seconds.
Can I mix Date and number inputs?
Yes. datetime.delta(new Date(), 0) works — numbers are treated as epoch milliseconds.
How to get the absolute time difference?
Use { abs: true }: datetime.delta(earlier, later, { abs: true }) always returns a positive number.
Does datetime.delta depend on Intl?
No. It uses pure arithmetic on epoch milliseconds. No platform dependencies.
What happens with invalid Date objects?
TypeError is thrown. Invalid dates (e.g. new Date('invalid')) are rejected.