Issue
I have two dates where I want to find the number of days between them, both dates inclusive.
I have following method:
numDaysBetweenDates(startDate, endDate) {
let millisecondsPerDay = 24 * 60 * 60 * 1000;
return (endDate - startDate) / millisecondsPerDay;
}
Suppose
startDate is Dec 12, 2019 11:49:55 PM
endDate is Dec 15, 2019 08:08:50 AM
Then I want the difference in days to be 4 (12,13,14,15).
The above method would return 2.xxx for the above input. It may also return 3.xxx if the startDate's time is before endDate's time. But I want the result to be 4.
How can I do this in Javascript or Angular?
Solution
you just need to set the same time for both dates before doing the difference (e.g. 00:00:00 000, assuming they have the same Time Zone, if they don't just set it to UTC). After doing this the division will give you an integer number that is the NON-inclusive difference between your dates. At this point all you have to do is to add 1 to the final result
EDIT: This is how you can change the time for your dates;
startDate = new Date(startDate);
endDate = new Date(endDate);
startDate.setHours(0,0,0,0);
endDate.setHours(0,0,0,0);
startDate = startDate.getTime();
endDate = endDate.getTime();
now in startDate and endDate you have the dates in milliseconds both starting at midnight and you can do your difference and division without the time influencing the result
Answered By - Francesco Di Stefano
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.