EN
JavaScript - get difference between two dates in days
1 answers
3 points
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:
xxxxxxxxxx
1
var date1 = new Date('5/10/2022');
2
var date2 = new Date('10/10/2022');
3
4
var result = date2.getDate() - date1.getDate();
5
6
console.log(result); // 0
1 answer
3 points
Warning:
Don't use
5/10/2022
or10/10/2022
formats to createDate
objects, it's non-standard and it's up to the browser how they are parsed.
You should:
- use subtraction to get the difference between two dates in milliseconds,
- then divide the difference by number of milliseconds in 1 day (
1000 * 60 * 60 * 24
) - then round it using one of the following methods:
Math.ceil()
,Math.round()
orMath.floor()
.
Practical example
xxxxxxxxxx
1
const date1 = new Date('2022-10-20T00:00:00.000Z'); // or just: 2022-10-20
2
const date2 = new Date('2022-10-25T01:00:00.000Z'); // or just: 2022-10-25
3
4
5
const milliseconds = date2 - date1; // difference in milliseconds
6
const days = Math.ceil(milliseconds / (1000 * 60 * 60 * 24)); // difference in days
7
8
console.log(days); // 6
Hint: consider to round
days
usingMath.ceil()
,Math.floor()
orMath.round()
methods if needed.
See also
References
0 commentsShow commentsAdd comment