react-date-object icon indicating copy to clipboard operation
react-date-object copied to clipboard

How to Calculate the Difference between the 2 date objects

Open viralchonkar opened this issue 2 years ago • 2 comments

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.

viralchonkar avatar Jun 16 '23 12:06 viralchonkar

You can use toDays() method.

const first = new DateObject();
const second = new DateObject().add(4, "days");

console.log(second.toDays() - first.toDays()); //4

shahabyazdi avatar Jun 16 '23 14:06 shahabyazdi

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.

viralchonkar avatar Jun 16 '23 14:06 viralchonkar