How can I subtract dates in JavaScript?
I have a field in a grid containing date/time, and I need to determine the difference between that date/time and the current date/time. What is the best way to achieve this?
The dates are stored in the format “2011-02-07 15:13:06”.
Hi,
You can convert the date string to a Date object and then subtract it from the current date to get the difference in milliseconds:
function getDateDifference(dateString) {
// Convert the date string to a Date object
const pastDate = new Date(dateString);
const currentDate = new Date();
// Calculate the difference in milliseconds
const difference = currentDate - pastDate; // milliseconds
// Convert milliseconds to days
const daysDifference = Math.floor(difference / (1000 * 60 * 60 * 24));
return daysDifference; // Return the difference in days
}
const dateStr = "2011-02-07 15:13:06";
console.log("Difference in days:", getDateDifference(dateStr));