Skip to content

Instantly share code, notes, and snippets.

@kuwabarahiroshi
Last active July 13, 2021 07:21
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 kuwabarahiroshi/600da54a46e984a6cb0ae5e0705662cb to your computer and use it in GitHub Desktop.
Save kuwabarahiroshi/600da54a46e984a6cb0ae5e0705662cb to your computer and use it in GitHub Desktop.
Vanilla JavaScript (ES6) Class that calculates monthly calendar object
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