Skip to content

Instantly share code, notes, and snippets.

@allenhwkim
Created July 2, 2020 18:03
Show Gist options
  • Select an option

  • Save allenhwkim/7e1d6a1224d923b91945810e61028cc2 to your computer and use it in GitHub Desktop.

Select an option

Save allenhwkim/7e1d6a1224d923b91945810e61028cc2 to your computer and use it in GitHub Desktop.
Calendar
import { Component, Output, EventEmitter } from '@angular/core';
const DAY_MS = 60 * 60 * 24 * 1000;
@Component({
selector: 'my-calendar',
templateUrl: './calendar.component.html',
styleUrls: [ './calendar.component.scss' ]
})
export class CalendarComponent {
dates: Array<Date>;
days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
date = new Date();
@Output() selected = new EventEmitter();
constructor() {
this.dates = this.getCalendarDays(this.date);
}
setMonth(inc) {
const [year, month] = [this.date.getFullYear(), this.date.getMonth()];
this.date = new Date(year, month + inc, 1);
this.dates = this.getCalendarDays(this.date);
}
isSameMonth(date) {
return date.getMonth() === this.date.getMonth();
}
private getCalendarDays(date = new Date) {
const calendarStartTime = this.getCalendarStartDay(date).getTime();
return this.range(0, 41)
.map(num => new Date(calendarStartTime + DAY_MS * num));
}
private getCalendarStartDay(date = new Date) {
const [year, month] = [date.getFullYear(), date.getMonth()];
const firstDayOfMonth = new Date(year, month, 1).getTime();
return this.range(1,7)
.map(num => new Date(firstDayOfMonth - DAY_MS * num))
.find(dt => dt.getDay() === 0)
}
private range(start, end, length = end - start + 1) {
return Array.from({ length }, (_, i) => start + i)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment