Reputation: 182
How to get the week count from the start date and end date using moment JS. Then I want to push it into an array. If a week is more than one week, I want to show like this const result = [1, 2, 3];
const dateStart = moment(1517812701107).format('DD-MM-YYYY');
const dateEnd = moment(1518331101107).format('DD-MM-YYYY');
From this start date and end date I need to get the number for week array. Is it possible in moment
JS.
Upvotes: 0
Views: 655
Reputation: 1859
First of all, you don't want to format your date just yet or you'll just have a string representation, not a moment instance. Once you've taken care of that it's as simple as using diff
:
const dateStart = moment(1517812701107);
const dateEnd = moment(1518331101107);
const weeksBetween = dateEnd.diff(dateStart, 'weeks');
As for turning that into a progression array, you could simply loop through the result:
const result = []
for (let i = 1; i <= weeksBetween; i++) {
result.push(i)
}
The timestamps you provided are less than a week apart and will result in 0
. If you are aiming to find the exact ratio, add a floating point flag for the third variable:
dateEnd.diff(dateStart, 'weeks', true); // 0.8571428571428571
Source: https://momentjs.com/docs/#/displaying/difference/
Upvotes: 1
Reputation: 656
You can try diff function, Try the following code. Hope this helps.
const dateStart = moment(1507812701107);
const dateEnd = moment(1518331101107);
const result = Array(dateEnd.diff(dateStart, 'week')).fill().map((e,i)=>i+1)
Upvotes: 0