Sorry if the question is a duplicate but I couldn't find anything on my case here.
I got a function getDaysDiff
where I pass two arguments (startDate, endDate)
which are date strings, and expect to get the difference between two dates in days but with some details.
Like so:
- If I pass
'2021-07-19T23:59:59'
and'2021-07-20T00:00:01'
I want to get 1 day as a return value because the dates are different even though the number of hours is less than 24 - Same for the case where the two dates are close but the number of hours is more than 24, like
'2021-07-19T00:00:01'
and'2021-07-20T23:59:59'
, in this case, I still want to get 1 day - And finally it should work as well with the adjacent dates from different months, like
'2021-07-30T23:59:59'
and'2021-08-01T00:00:01'
should return 1 day as well.
I tried to apply the following function but thanks to Math.round/floor/ceil
it breaks anyways for one of the cases above.
function getDaysDiff(start, end) {
const date1 = new Date(start);
const date2 = new Date(end);
const oneDay = 1000 * 60 * 60 * 24;
const diffInTime = date2.getTime() - date1.getTime();
const diffInDays = Math.ceil(diffInTime / oneDay);
return diffInDays;
}
console.log(getDaysDiff('2021-07-19T23:59:59', '2021-07-20T00:00:01'));
console.log(getDaysDiff('2021-07-19T00:00:01', '2021-07-20T23:59:59'));
console.log(getDaysDiff('2021-07-31T23:59:59', '2021-08-01T00:00:01'));
Is there a consice way to get this difference?