Last active
July 13, 2021 07:21
-
-
Save kuwabarahiroshi/600da54a46e984a6cb0ae5e0705662cb to your computer and use it in GitHub Desktop.
Vanilla JavaScript (ES6) Class that calculates monthly calendar object
This file contains 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
export default class Calendar { | |
constructor(...args) { | |
this.date = new Date(...args); | |
} | |
get year() { | |
return this.date.getFullYear(); | |
} | |
get month() { | |
return this.monthIndex + 1; | |
} | |
get monthIndex() { | |
return this.date.getMonth(); | |
} | |
beginningOfMonth(diff = 0) { | |
// NOTE: it's safe to add diff to monthIndex even if it's Jan or Dec. | |
return new Date(this.year, this.monthIndex + diff); | |
} | |
get nextMonth() { | |
return this.beginningOfMonth(1); | |
} | |
get lastMonth() { | |
return this.beginningOfMonth(-1); | |
} | |
get next() { | |
return new Calendar(this.nextMonth); | |
} | |
get prev() { | |
return new Calendar(this.lastMonth); | |
} | |
get firstDay() { | |
return this.beginningOfMonth().getDay(); | |
} | |
get daysInMonth() { | |
return 32 - new Date(this.year, this.monthIndex, 32).getDate(); | |
} | |
get weeks() { | |
const { year, monthIndex, firstDay, daysInMonth } = this; | |
const weeks = []; | |
let date = 1; | |
for (let week = 0; week < 6; week++) { | |
if (date > daysInMonth) { break; } | |
const days = []; | |
for (let day = 0; day < 7; day++) { | |
if (week === 0 && day < firstDay) { | |
days.push(new Date(year, monthIndex, day - firstDay + 1)); | |
} else { | |
days.push(new Date(year, monthIndex, date++)); | |
} | |
} | |
weeks.push(days); | |
} | |
return weeks; | |
} | |
eq(other) { | |
return (this - other) === 0; | |
} | |
valueOf() { | |
return this.beginningOfMonth().valueOf(); | |
} | |
toString() { | |
let { year, month } = this; | |
month = `0${month}`.substr(-2); | |
return `${year}-${month}-01`; | |
} | |
includes(date) { | |
return date.getFullYear() == this.year && date.getMonth() == this.monthIndex; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment