Issue
I try to create a list of days between two days.
I created solution like this:
this.daysBetween = [];
while (dateFrom.getDate() !== dateTo.getDate()+1 ) {
this.daysBetween.push(this.dateFrom);
dateFrom.setDate(dateFrom.getDate()+1);
}
But it works only in 90% cases (if there is month change it doesn't work)
e.g. when I pick dates:
dateFrom: 29 august
dateTo: 30 august
it prints me days from 29 august till 30 september ignoring 31 august ...
Any ideas how to fix my solution, or maybe there is better one?
EDIT:
My question is different than question suggested, because in my question I have as input two dates
e.g.
let dateFrom = new Date(2018, 9, 29);
let dateTo = new Date(2018, 9, 30);
On suggested duplicate result of this could have been int number 1
My question is how to loop through all days between two dates (dateFrom, dateTo)
Where result of those 2 dates examples (dateFrom, dateTo)
would've been list with 2 elements:
Mon Oct 29 2018 00:00:00 GMT+0100
Tue Oct 30 2018 00:00:00 GMT+0100
Solution
You could calculate the difference in milliseconds, and then convert that into the difference in days.
You can then use this to fill an array with Date objects:
const MS_PER_DAY: number = 1000 x 60 x 60 x 24;
const start: number = dateFrom.getTime();
const end: number = dateTo.getTime();
const daysBetweenDates: number = Math.ceil((end - start) / MS_PER_DAY);
// The days array will contain a Date object for each day between dates (inclusive)
const days: Date[] = Array.from(new Array(daysBetweenDates + 1),
(v, i) => new Date(start + (i * MS_PER_DAY)));
Answered By - duncanhall
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.