Last active
May 24, 2024 06:13
-
-
Save guillaumepiot/095b5e02b4ca22680a50 to your computer and use it in GitHub Desktop.
Get all the weeks in a given month and year using Moment.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# year and month are variables | |
year = 2015 | |
month = 7 # August (0 indexed) | |
startDate = moment([year, month]) | |
# Get the first and last day of the month | |
firstDay = moment(startDate).startOf('month') | |
endDay = moment(startDate).endOf('month') | |
# Create a range for the month we can iterate through | |
monthRange = moment.range(firstDay, endDay) | |
# Get all the weeks during the current month | |
weeks = [] | |
monthRange.by('days', (moment)-> | |
if moment.week() not in weeks | |
weeks.push(moment.week()) | |
) | |
# Create a range for each week | |
calendar = [] | |
for week in weeks | |
# Create a range for that week between 1st and 7th day | |
firstWeekDay = moment().week(week).day(1) | |
lastWeekDay = moment().week(week).day(7) | |
weekRange = moment.range(firstWeekDay, lastWeekDay) | |
# Add to the calendar | |
calendar.push(weekRange) | |
console.log calendar |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ok, changing firstWeekDay to 0 and lastWeekDay to 6 (week starts at Sunday) fixes the problem: