How To Calculate Difference Between Dates in JavaScript with date-fns

node v18.11.0
version: 2.0.0
endpointsharetweet
// import isn't supported in Node v18.11.0 otherwise it would be // import { differenceInSeconds, differenceInMinutes, differenceInHours, differenceInDays, differenceInCalendarDays, differenceInBusinessDays, differenceInWeeks, differenceInCalendarWeeks, differenceInMonths, differenceInCalendarMonths, differenceInQuarters, differenceInCalendarQuarters, differenceInYears, differenceInCalendarYears } from 'date-fns' const dateFns = require( "date-fns"); const { differenceInSeconds, differenceInMinutes, differenceInHours, differenceInDays, differenceInCalendarDays, differenceInBusinessDays, differenceInWeeks, differenceInCalendarWeeks, differenceInMonths, differenceInCalendarMonths, differenceInQuarters, differenceInCalendarQuarters, differenceInYears, differenceInCalendarYears } = dateFns; // 31th of January 2023 const fromDate = new Date(2023, 0, 31); const toDate = new Date(2025, 7, 15); console.log(`Diff in seconds: ${differenceInSeconds(toDate, fromDate)}`) console.log(`Diff in minutes: ${differenceInMinutes(toDate, fromDate)}`) console.log(`Diff in hours: ${differenceInHours(toDate, fromDate)}`) console.log(`Diff in days: ${differenceInDays(toDate, fromDate)}`) console.log(`Diff in business days: ${differenceInBusinessDays(toDate, fromDate)}`) console.log(`Diff in calendar days: ${differenceInCalendarDays(toDate, fromDate)}`) console.log(`Diff in weeks: ${differenceInWeeks(toDate, fromDate)}`) console.log(`Diff in calendar weeks: ${differenceInCalendarWeeks(toDate, fromDate)}`) console.log(`Diff in months: ${differenceInMonths(toDate, fromDate)}`) console.log(`Diff in calendar months: ${differenceInCalendarMonths(toDate, fromDate)}`) console.log(`Diff in quarters: ${differenceInQuarters(toDate, fromDate)}`) console.log(`Diff in calendar quarters: ${differenceInCalendarQuarters(toDate, fromDate)}`) console.log(`Diff in years: ${differenceInYears(toDate, fromDate)}`) console.log(`Diff in calendar years: ${differenceInCalendarYears(toDate, fromDate)}`)
Loading…

no comments

    sign in to comment