Skip to content

Instantly share code, notes, and snippets.

@techniq
Last active April 20, 2017 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techniq/90dd698af9fafc01e9eb830421910359 to your computer and use it in GitHub Desktop.
Save techniq/90dd698af9fafc01e9eb830421910359 to your computer and use it in GitHub Desktop.
Get calendar days
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