74 lines
2.3 KiB
JavaScript
74 lines
2.3 KiB
JavaScript
const weekDayNumber = 7
|
|
const week_zh_cn = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
|
|
const week_en_us = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT']
|
|
|
|
class Day {
|
|
constructor(year, month, day, content, isCurrentMonth = false, isCurrentDay = false) {
|
|
this.year = year
|
|
this.month = month
|
|
this.day = day
|
|
this.content = content
|
|
this.isCurrentMonth = isCurrentMonth
|
|
this.isCurrentDay = isCurrentDay
|
|
}
|
|
}
|
|
|
|
const defaultDate = new Date()
|
|
const defaultYear = defaultDate.getFullYear()
|
|
const defaultMonth = defaultDate.getMonth()
|
|
const defaultDay = defaultDate.getDate()
|
|
|
|
/**
|
|
* 初始化日历
|
|
* @param {[Day]} currentDays
|
|
* @param {number} [year = defaultYear]
|
|
* @param {number} [month = defaultMonth]
|
|
* @param {number} [day = defaultDay]
|
|
* @returns {[Day]}
|
|
*/
|
|
function initDay(
|
|
currentDays = new Array(42),
|
|
year = defaultYear,
|
|
month = defaultMonth,
|
|
day = defaultDay
|
|
) {
|
|
if (!Array.isArray(currentDays)) {
|
|
currentDays = new Array(42)
|
|
} else if (currentDays.length !== 42) {
|
|
console.log(currentDays)
|
|
throw new Error('currentDays:' + currentDays)
|
|
} else {
|
|
currentDays = [...currentDays]
|
|
}
|
|
|
|
const days = currentDays
|
|
const lastDayOfLastMonth = new Date(year, month, 0)
|
|
const firstDayOfMonth = new Date(year, month, 1)
|
|
const lastDayOfMonth = new Date(year, month + 1, 0)
|
|
const currentDaysOfMonth = lastDayOfMonth.getDate()
|
|
const daysOfLastMonth = lastDayOfLastMonth.getDate()
|
|
|
|
for (let i = 0; i < firstDayOfMonth.getDay(); i++) {
|
|
const weekDay = firstDayOfMonth.getDay() - 1
|
|
days[i] = new Day(year, month - 1, daysOfLastMonth - weekDay + i, week_zh_cn[i])
|
|
}
|
|
|
|
for (let i = 0; i < currentDaysOfMonth; i++) {
|
|
const weekDay = (firstDayOfMonth.getDay() + i) % weekDayNumber
|
|
days[firstDayOfMonth.getDay() + i] = new Day(year, month, i + 1, week_zh_cn[weekDay], true)
|
|
if (i === day - 1) {
|
|
days[firstDayOfMonth.getDay() + i].isCurrentDay = true
|
|
}
|
|
}
|
|
|
|
for (let i = currentDaysOfMonth + firstDayOfMonth.getDay(); i < days.length; i++) {
|
|
const extraDay = i - currentDaysOfMonth - firstDayOfMonth.getDay() + 1
|
|
const weekDay = i % weekDayNumber
|
|
days[i] = new Day(year, month + 1, extraDay, week_zh_cn[weekDay])
|
|
}
|
|
|
|
return currentDays
|
|
}
|
|
|
|
export { week_zh_cn, week_en_us, defaultYear, defaultMonth, defaultDay, initDay }
|