How To Find Milliseconds Difference Between Two Dates In JavaScript

JavaScript allows you to create two Date objects and use the getTime() function to subtract the values to determine the milliseconds that separate two dates. The difference in milliseconds between the dates will be the outcome.

Here’s an example,

const date1 = new Date();
// Wait for a few milliseconds
setTimeout(() =>
{
    const date2 = new Date();
    const diffInMs = date2.getTime() - date1.getTime();
    console.log(diffInMs);
    },
100);
  • Date1 in this illustration represents the time and date at which it was made. With setTimeout, we wait for 100 milliseconds before creating date2. Then, using getTime, the difference between the two dates is determined (). The outcome will be the difference in milliseconds, which should be around 100 between the two dates.

You can also subtract two Date objects directly to get the difference in milliseconds, like this,

const date1 = new Date();
// Wait for a few milliseconds
setTimeout(() =>
{
    const date2 = new Date();
    const diffInMs = date2 - date1; console.log(diffInMs);
  },
100);

This will also give you the difference between the two dates in milliseconds.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories