Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to Calculate the Difference between the 2 date objects #6

Open
viralchonkar opened this issue Jun 16, 2023 · 2 comments
Open

How to Calculate the Difference between the 2 date objects #6

viralchonkar opened this issue Jun 16, 2023 · 2 comments

Comments

@viralchonkar
Copy link

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.

@shahabyazdi
Copy link
Owner

You can use toDays() method.

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

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

@viralchonkar
Copy link
Author

viralchonkar commented Jun 16, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants