Skip to content

Instantly share code, notes, and snippets.

@f-ricci
Forked from markthiessen/getWeeksInMonth.js
Created August 31, 2021 16:27
Show Gist options
  • Save f-ricci/b20db934485c9351e16459f32a8a0e40 to your computer and use it in GitHub Desktop.
Save f-ricci/b20db934485c9351e16459f32a8a0e40 to your computer and use it in GitHub Desktop.
JavaScript - get weeks in a month as array of start and end days
//note: month is 0 based, just like Dates in js
function getWeeksInMonth(year, month) {
const weeks = [],
firstDate = new Date(year, month, 1),
lastDate = new Date(year, month + 1, 0),
numDays = lastDate.getDate();
let dayOfWeekCounter = firstDate.getDay();
for (let date = 1; date <= numDays; date++) {
if (dayOfWeekCounter === 0 || weeks.length === 0) {
weeks.push([]);
}
weeks[weeks.length - 1].push(date);
dayOfWeekCounter = (dayOfWeekCounter + 1) % 7;
}
return weeks
.filter((w) => !!w.length)
.map((w) => ({
start: w[0],
end: w[w.length - 1],
dates: w,
}));
}
exports.getWeeksInMonth = getWeeksInMonth;
const getWeeksInMonth = require("./getWeeksInMonth").getWeeksInMonth;
describe("getWeeksInMonth", () => {
test("June 2019 (starts on Saturday)", () => {
const weeks = getWeeksInMonth(2019, 5);
expect(weeks.length).toBe(6);
expect(weeks[0].start).toBe(1);
expect(weeks[0].end).toBe(1);
});
test("Feb 2021 (starts on Monday)", () => {
const weeks = getWeeksInMonth(2021, 1);
expect(weeks.length).toBe(5);
expect(weeks[0].start).toBe(1);
expect(weeks[0].end).toBe(6);
expect(weeks[4].start).toBe(28);
expect(weeks[4].end).toBe(28);
});
test("Aug 2021 (starts on Sunday)", () => {
const weeks = getWeeksInMonth(2021, 7);
expect(weeks.length).toBe(5);
expect(weeks[0].start).toBe(1);
expect(weeks[0].end).toBe(7);
expect(weeks[4].start).toBe(29);
expect(weeks[4].end).toBe(31);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment