日历js
const calendar: any = {};
let today = new Date();
calendar.getMonthDate = function (
year = today.getFullYear(),
month = today.getMonth() + 1
) {
const firstDay = new Date(year, month - 1, 1);
let firstDayWeekDay = firstDay.getDay();
if (firstDayWeekDay === 0) firstDayWeekDay = 7;
year = firstDay.getFullYear();
month = firstDay.getMonth() + 1;
const lastDayofLastMonth = new Date(year, month - 1, 0);
const lastDateofLastMonth = lastDayofLastMonth.getDate();
const preMonthDayCount = firstDayWeekDay;
const lastDay = new Date(year, month, 0);
const lastData = lastDay.getDate();
const ret: any[] = [];
for (let i = 0; i < 6 * 7; i++) {
const date = i + 1 - preMonthDayCount;
let showDate = date;
let thisMonth = month;
if (date <= 0) {
thisMonth = month - 1;
showDate = lastDateofLastMonth + date;
} else if (date > lastData) {
thisMonth = month + 1;
showDate = showDate - lastData;
}
if (thisMonth === 13) thisMonth = 1;
if (thisMonth === 0) thisMonth = 12;
ret.push({
date: new Date(year, thisMonth - 1, showDate),
data: `${year}-${String(thisMonth).padStart(2, "0")}-${String(
showDate
).padStart(2, "0")}`
});
}
return {
days: ret,
today: today
};
};
calendar.preMonth = function () {
let thisMonth = today.getMonth();
let thisYear = today.getFullYear();
thisMonth--;
if (thisMonth === 0) {
thisMonth = 12;
thisYear--;
}
today = new Date(thisYear, thisMonth, 1);
return this.getMonthDate();
};
calendar.today = function () {
today = new Date();
return this.getMonthDate();
};
calendar.nextMonth = function () {
let thisMonth = today.getMonth();
let thisYear = today.getFullYear();
thisMonth++;
if (thisMonth === 13) {
thisMonth = 1;
thisYear++;
}
today = new Date(thisYear, thisMonth, 1);
return this.getMonthDate();
};
calendar.format = (format: string, date: any) => {
const obj = {
yyyy年MM月: () =>
`${date.getFullYear()}年${String(date.getMonth() + 1).padStart(2, "0")}月`
};
return obj[format] && obj[format]();
};
export default calendar;