differenceInDays
The differenceInDays utility function calculates the number of whole days between two dates. It simplifies date calculations in JavaScript by accepting flexible input types. The first parameter represents the reference date from which the difference is measured, and the second parameter denotes the date to be compared against the reference date. Both parameters accept Date objects, numbers representing milliseconds since the Unix epoch, or strings parseable by the Date constructor.
Examples
Example 1: Calculate Days Between Dates
Calculate the number of whole days between two dates using different input types:
import {differenceInDays} from 'ngx-lift';
console.log(differenceInDays(new Date('2022-09-08'), new Date('2023-09-18')));
console.log(differenceInDays('2022-09-08', '2023-09-18'));
console.log(differenceInDays('2022-09-08', new Date('2023-09-18')));
Example 2: Calculate Days from Today
Calculate the number of days from today to a specific date:
import {differenceInDays} from 'ngx-lift';
const daysAgo = differenceInDays(new Date(), '2022-09-08');
console.log(`That date was ${daysAgo} days ago`);
const daysAgo2 = differenceInDays(Date.now(), '2022-09-08');
console.log(`That date was ${daysAgo2} days ago`);
API Reference
differenceInDays
Calculates the number of whole days between two dates.
Signature
differenceInDays(dateLeft: Date | number | string, dateRight: Date | number | string): number
Parameters
dateLeft: Date | number | string The reference date. Can be a Date object, a number (milliseconds since Unix epoch), or a string parseable by the Date constructor.
dateRight: Date | number | string The date to compare against the reference date. Accepts the same types as dateLeft.
Returns
The number of whole days between the two dates. Returns a positive number if dateLeft is later than dateRight, and a negative number if dateLeft is earlier than dateRight.