Skip to content

Instantly share code, notes, and snippets.

@rockonyu
Last active July 11, 2020 18:58
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 rockonyu/be1354fbc86771370c4602e65b086cf1 to your computer and use it in GitHub Desktop.
Save rockonyu/be1354fbc86771370c4602e65b086cf1 to your computer and use it in GitHub Desktop.
another-calendar
const totalCells = 42;
const startDay = 0;
const addDays = (date: Date, days: number) => {
return new Date(new Date(date).setDate(date.getDate() + days));
};
const render = (year: number, month: number) => {
const firstDate = new Date(year, month, 1);
const lastDate = new Date(year, month + 1, 0);
const startDateOnCalendar = addDays(firstDate, startDay - firstDate.getDay());
let output = "";
for (let i = 0; i < totalCells; i++) {
const currentDate = addDays(startDateOnCalendar, i);
let formatStr = `00${currentDate.getDate()} `.slice(-3);
if (currentDate >= firstDate && currentDate <= lastDate) {
formatStr = formatStr.replace(" ", ".");
}
output += formatStr;
if (i % 7 === 6) {
console.log(output);
output = "";
}
}
};
for (let i = 0; i < 12; i++) {
console.log(`======= ${i + 1}月 =======`);
render(2020, i);
}
type FullYear = {
year: number;
months: Array<number[]>;
};
const processYear = (year: number): FullYear => {
const fullYear: FullYear = {
year,
months: [],
};
for (let i = 0; i < 12; i++) {
const month = [];
const firstDate = new Date(year, i, 1);
const lastDate = new Date(year, i + 1, 0);
const offset = firstDate.getDay();
for (let j = 0; j < lastDate.getDate(); j++) {
month[j + offset] = j + 1;
}
fullYear.months.push(month);
}
return fullYear;
};
const render = (queryYear: number) => {
const { year, months } = processYear(queryYear);
const totalCells = 42;
console.log(`\n${year}:`);
for (let counter = 0; counter < months.length; counter++) {
console.log(`\n${counter + 1} 月`);
let currentLine = "";
for (let cell = 0; cell < totalCells; cell++) {
const day = months[counter][cell]
? ` ${months[counter][cell]} `.slice(-3)
: "___";
currentLine += day;
if (cell % 7 === 6) {
console.log(currentLine);
currentLine = "";
}
}
}
};
const year = +Deno.args[0] || new Date().getFullYear();
console.time("process");
render(year);
console.timeEnd("process");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment