-
-
Save vigosan/cc5f1045dc0f41a8fc63cc50b0ca5416 to your computer and use it in GitHub Desktop.
JavaScript - get weeks in a month as array of start and end days
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
//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; |
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
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