Title: Iterating over weeks in date-fns
Tags: javascript;ecmascript-6;date-fns
Question: I'm using the date-fns library to build a calendar, and I need to get the weeks for a month.
let start = startOfMonth(date)
let end = endOfMonth(date)
let firstWeek = getISOWeek(start)
let lastWeek = getISOWeek(end)
let weeks = []
for (let i = firstWeek; i < lastWeek + 1; i++) {
weeks.push(i)
return weeks
This works well for most months, except for the month of December, where weeks is empty because firstWeek and lastWeek are "48" and "1" respectively.
I know I can fix this with a more complex loop, to check if each iteration is higher or lower than the previous, but I'm wondering if there's a more natural/simple way to achieve this using date-fns (or es6).


Here is another answer: Would be better to defer getting of the ISO week and iterate over the actual dates, instead of dealing with week index numbers.
let startOfCurrent = startOfMonth(date)
let startOfNext = addMonths(startOfCurrent, 1)
let weeks = []
for (let i = startOfCurrent; isBefore(i, startOfNext); i = addWeeks(i, 1)) {
weeks.push(getISOWeek(i))
return weeks

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2018:00:07/06/18', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><ecmascript-6><date-fns>', 'Title': 'Iterating over weeks in date-fns', 'ViewCount': 1042, 'id': 51217410, 'user_AboutMe': '<p>Javascript, React, HTML5, CSS3, Bootstrap, Python &amp; Django.</p>\n', 'user_AccountId': 4983861.0, 'user_DisplayName': 'Toby', 'user_Reputation': 11991.0, 'user_Views': 565.0, 'user_id': 4008056.0}}