ArticleZip > Javascript Get Minutes Between Two Dates

Javascript Get Minutes Between Two Dates

Imagine you're building a web application where you need to calculate the minutes between two dates using JavaScript. Don't worry; it's easier than you might think! In this article, we'll walk you through the steps to achieve this.

To get the minutes between two dates in JavaScript, you can use the Date object. Here's a simple approach to calculate this:

Javascript

// Define two dates
const date1 = new Date('2022-10-10 10:00:00');
const date2 = new Date('2022-10-10 12:30:00');

// Calculate the difference in milliseconds
const diffInMilliseconds = date2 - date1;

// Convert milliseconds to minutes
const diffInMinutes = diffInMilliseconds / (1000 * 60);

console.log(diffInMinutes); // Output: 150

In the above code snippet, we create two Date objects representing the two dates for which we want to find the difference in minutes. By subtracting one date from the other, we get the difference in milliseconds. Then, by dividing this difference by 1000 (to convert milliseconds to seconds) and further dividing by 60 (to convert seconds to minutes), we obtain the minutes between the two dates.

If you want a more readable and reusable solution, you can encapsulate this logic in a function:

Javascript

function getMinutesBetweenDates(date1, date2) {
  const diffInMilliseconds = date2 - date1;
  return diffInMilliseconds / (1000 * 60);
}

const date1 = new Date('2022-10-10 14:00:00');
const date2 = new Date('2022-10-10 15:45:00');
console.log(getMinutesBetweenDates(date1, date2)); // Output: 105

With this function, you can easily calculate the minutes between any two dates by passing the Date objects as arguments to the function.

It's important to note that the result will be a floating-point number, so if you prefer to have a whole number of minutes (e.g., rounding down or up), you can use `Math.floor()` or `Math.ceil()`, respectively, on the result.

That's it! You now have the tools to effortlessly calculate the minutes between two dates in JavaScript. Experiment with the code examples provided and modify them to fit your specific requirements. Happy coding!