Last active
August 2, 2018 21:04
-
-
Save DaBs/56b6ee15d02748cde85d972f8ab6a068 to your computer and use it in GitHub Desktop.
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 MILISECONDS_IN_A_DAY = 1000 * 60 * 60 * 24; | |
const getDaysInMonth = (month, year = (new Date()).getFullYear()) => { | |
return new Date(year, month + 1, 0).getDate(); | |
} | |
const getMonday = (d) => { | |
const parsedDate = new Date(d); | |
const day = parsedDate.getDay(); | |
const difference = parsedDate.getDate() - day + (day == 0 ? -6 : 1); | |
return new Date(parsedDate.setDate(difference)); | |
} | |
const getDateDifference = (firstDate, secondDate) => { | |
return Math.ceil(Math.abs(firstDate.getTime() - secondDate.getTime()) / MILISECONDS_IN_A_DAY); | |
} | |
const getDaysForMonthFormatted = (month, year = (new Date()).getFullYear()) => { | |
const firstDateOfMonth = new Date(year, month, 1); | |
const lastMonday = getMonday(firstDateOfMonth); | |
const difference = getDateDifference(firstDateOfMonth, lastMonday); | |
const daysInMonth = getDaysInMonth(month, year); | |
const days = new Array(42).fill(0).map( (_, index) => { | |
return new Date(year, month, index + 1 - difference); | |
}); | |
return days; | |
} | |
new Array(12).fill(0).reduce( (totalDays, item, monthIndex) => { | |
var daysInThisMonth = daysInMonth(monthIndex, currentYear); | |
var datesInThisMonth = new Array(daysInThisMonth).fill(0).map((_, dayIndex) => { | |
return new Date(currentYear, monthIndex, dayIndex + 1); | |
}); | |
return totalDays.concat(datesInThisMonth); | |
}, []); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment