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 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 |
In line 24 and 25 the initial parameters for the date are missing.
translated to javascript:
npm install moment moment-range
import * as Moment from 'moment';
import { extendMoment } from 'moment-range';
export const getDaysInAMonth = (year = +Moment().format("YYYY"), month = +Moment().format("MM") - 1) => {
const moment = extendMoment(Moment);
const startDate = moment([year, month]);
const firstDay = moment(startDate).startOf('month')
const endDay = moment(startDate).endOf('month')
const monthRange = moment.range(firstDay, endDay)
const weeks = [];
const days = Array.from(monthRange.by('day'));
days.forEach(it => {
if (!weeks.includes(it.week())) {
weeks.push(it.week());
}
})
const calendar = []
weeks.forEach(week => {
const firstWeekDay = moment([year, month]).week(week).day(1)
const lastWeekDay = moment([year, month]).week(week).day(7)
const weekRange = moment.range(firstWeekDay, lastWeekDay)
calendar.push(Array.from(weekRange.by('day')));
})
return calendar;
}
thanks for your code! :)
Good observation, would default to current year otherwise.
I found a problem, February 2021 returns March 1-7 as a week (instead of stopping at February 22-28)
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
range function does not even exist, right?