Find Weeks of the Month with JavaScript Moment JS
While working with the date we always have a new challenge, this time we were working on a react-native project and we found the requirement to find Weeks of the Month in JavaScript. We have used Moment JS here.
Once we started researching on it, soon we concluded that we will have to modify examples as per our requirement and we end up with simple and elegant JavaScript code with the support of moment and moment-range. Below is working jsbin
Explanation of logic used
Getting the first and last day of the Month
firstDay = moment(startDate).startOf('month') endDay = moment(startDate).endOf('month')
The next step is to find out a number of weeks in this month, we need to use moment range here.
monthRange = moment.range(firstDay, endDay); weeks = [] for (let mday of monthRange.by('days')) { if (weeks.indexOf(mday.week()) === -1) { weeks.push(mday.week()); } }
This will prepare array with number of weeks.
Now we just need to loop through it as below:
calendar = [] for (let index = 0; index < weeks.length; index++) { var weeknumber = weeks[index]; firstWeekDay = moment(firstDay).week(weeknumber).day(0); if (firstWeekDay.isBefore(firstDay)) { firstWeekDay = firstDay; } lastWeekDay = moment(endDay).week(weeknumber).day(6); if (lastWeekDay.isAfter(endDay)) { lastWeekDay = endDay; } weekRange = moment.range(firstWeekDay, lastWeekDay) calendar.push(weekRange) }
Calendar contains range of weeks for month.
If you have any query, feel free to comment.