Calculate the difference between two dates

By Hunter Becton on January 21, 2023

const dateDiff = (date1, date2) => Math.abs(new Date(date1) - new Date(date2));

How it works

This function takes two arguments, which should be valid JavaScript date formats, and returns the difference between the two dates in milliseconds. For example, the difference between 2023-01-21 19:07:38.578106+00 and 2023-01-03 19:07:38.578106+00 would return 1555200000.

Be careful with the arguments that you pass into this function. When possible, use an ISO-8601-compliant date because you will work more reliably across different runtimes.