Last active
April 20, 2017 19:48
-
-
Save techniq/90dd698af9fafc01e9eb830421910359 to your computer and use it in GitHub Desktop.
Get calendar 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
import dateFns from 'date-fns'; | |
function getMonthDays(date) { | |
const startOfMonth = dateFns.startOfMonth(date); | |
const endOfMonth = dateFns.endOfMonth(date); | |
let prevMonthDaysNeeded = startOfMonth.getDay(); | |
const prevMonthDays = prevMonthDaysNeeded ? dateFns.eachDay( | |
dateFns.subDays(startOfMonth, prevMonthDaysNeeded), | |
dateFns.subDays(startOfMonth, 1) | |
) : []; | |
const currentMonthDays = dateFns.eachDay(startOfMonth, endOfMonth); | |
const lastWeekDays = (prevMonthDays.length + currentMonthDays.length) % 7; | |
const nextMonthDaysNeeded = lastWeekDays === 0 ? 0 : 7 - lastWeekDays; | |
const nextMonthDays = nextMonthDaysNeeded ? dateFns.eachDay( | |
dateFns.addDays(endOfMonth, 1), | |
dateFns.addDays(endOfMonth, nextMonthDaysNeeded) | |
) : []; | |
return { | |
previous: prevMonthDays, | |
current: currentMonthDays, | |
next: nextMonthDays, | |
}; | |
} | |
console.log('Now', getMonthDays(new Date())); | |
console.log('September', getMonthDays(new Date(2017,8,1))); | |
console.log('October', getMonthDays(new Date(2017,9,1))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment