Get difference between two dates in nodejs

Webstorm Visual Studio Code

Create two Date objects representing the dates you want to compare. Calculate the difference in milliseconds using the subtraction operator (-). Convert the milliseconds difference to the desired time units (e.g., seconds, minutes, hours, days) if needed.

You can use the Date object in JavaScript to get the difference between two dates in Node.js. Here's an example of how you can do it:

// Define two dates
const date1 = new Date('2022-01-01');
const date2 = new Date('2022-01-10');

// Calculate the difference in milliseconds
const differenceInMilliseconds = Math.abs(date2 - date1);

// Calculate the difference in seconds
const differenceInSeconds = differenceInMilliseconds / 1000;

// Calculate the difference in minutes
const differenceInMinutes = differenceInSeconds / 60;

// Calculate the difference in hours
const differenceInHours = differenceInMinutes / 60;

// Calculate the difference in days
const differenceInDays = differenceInHours / 24;

console.log(`Difference in milliseconds: ${differenceInMilliseconds}`);
console.log(`Difference in seconds: ${differenceInSeconds}`);
console.log(`Difference in minutes: ${differenceInMinutes}`);
console.log(`Difference in hours: ${differenceInHours}`);
console.log(`Difference in days: ${differenceInDays}`);

In this example, date1 and date2 are two JavaScript Date objects representing the dates you want to compare. The difference is calculated in milliseconds first, and then converted to seconds, minutes, hours, and days.

Keep in mind that this code assumes that date1 is before date2. If date2 is before date1, you may want to swap their positions or handle the negative difference accordingly.

Also, if you want to use the current date, you can create a Date object without passing any arguments like this:

const currentDate = new Date();

Then, you can use currentDate in place of date1 or date2 in the above code.

Comments
Loading...
Sorry! No comment found:(

There is no comment to show for this.

Leave your comment
Tested Versions
  • Nodejs 18