Languages

JavaScript - get difference between two dates in days

3 points
Asked by:
Laylah-Walsh
624

How can I get the difference between two dates in full days?

I don't want any fractions of a day, like 2.5 days.

For example:

1 answer
3 points
Answered by:
Admin Dirask Community
4380

Warning:

Don't use 5/10/2022 or 10/10/2022 formats to create Date objects, it's non-standard and it's up to the browser how they are parsed.

 

You should:

  1. use subtraction to get the difference between two dates in milliseconds,
  2. then divide the difference by number of milliseconds in 1 day (1000 * 60 * 60 * 24)
  3. then round it using one of the following methods: Math.ceil(), Math.round() or Math.floor().

Practical example

Hint: consider to round days using Math.ceil()Math.floor() or Math.round() methods if needed.

 

See also

  1. JavaScript - calculate days difference between two dates

  2. ISO 8601 - Z meaning in yyyy-MM-ddTHH:mm:ssZ date time format

References

  1. Math.round() - JavaScript | MDN
  2. Math.ceil() - JavaScript | MDN
  3. Math.floor() - JavaScript | MDN
  4. Math.abs() - JavaScript | MDN
0 commentsAdd comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join