react-date-object
react-date-object copied to clipboard
How to Calculate the Difference between the 2 date objects
How to calculate the difference between the 2 date objects? For eg.: let currentDate = new DateObject(); let previousDate = new DateObject(4,'days'); let difference = previousDate - currentDate; // Which will be 4 in number
Suggestion would help me out.
You can use toDays() method.
const first = new DateObject();
const second = new DateObject().add(4, "days");
console.log(second.toDays() - first.toDays()); //4
But it will not work in case of days will include multiple months.
Though, We found one Solution to this,
const getDiffInDays = (date1: DateObject, date2: DateObject) => { let newDate = date1.valueOf(); let newDate1 = date2.valueOf(); let diff = Math.abs(newDate1 - newDate); return Math.ceil(diff / (1000 * 60 * 60 * 24)); };
Converted the dates in milliseconds and after difference calculated the days.