Skip to content

Instantly share code, notes, and snippets.

@guillaumepiot
Last active March 8, 2023 07:34
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save guillaumepiot/095b5e02b4ca22680a50 to your computer and use it in GitHub Desktop.
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
# 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
@andresilva-cc
Copy link

Ok, changing firstWeekDay to 0 and lastWeekDay to 6 (week starts at Sunday) fixes the problem:

const firstWeekDay = moment([year, month]).week(week).day(0);
const lastWeekDay = moment([year, month]).week(week).day(6);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment