1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- const getCalendar = function (date) {
- // 日历布局 ( 0-6,0代表星期天)
- let weeks = [1, 2, 3, 4, 5, 6, 0]
- // 拆分日期
- let year = date.split("-")[0]
- let month = date.split("-")[1]
- let day = date.split("-")[2]
- // 创建置顶日期的日期对象
- let myDate = new Date(date)
- // 获取当前月总天数
- let days = new Date(year, month, 0).getDate()
- // 计算日历面板需要展示上月的天数
- let showLastNum = weeks.indexOf(myDate.getDay())
- // 计算上月的年、月
- let lastYear = Number(month) > 1 ? year : year - 1
- let lastMonth = Number(month) > 1 ? Number(month) - 1 : 12
- lastMonth = lastMonth < 10 ? '0' + lastMonth : lastMonth
- // 计算下月的年、月
- let nextYear = Number(month) < 12 ? year : year + 1
- let nextMonth = Number(month) < 12 ? Number(month) + 1 : '01'
- nextMonth = nextMonth < 10 ? '0' + nextMonth : nextMonth
- // 计算上月总天数
- let lastMonthDays = new Date(lastYear, lastMonth, 0).getDate()
- // 生成日历数组 【年、月、日,是分开的,方便自定义样式】
- let calendar = []
- for (let i = 0; i < 42; i++) {
- if (i < showLastNum) {
- let info = {
- day: String(lastMonthDays - (showLastNum - 1 - i)),
- month: String(lastMonth),
- year: String(lastYear)
- }
- calendar.push(info)
- } else if (i < (showLastNum + days)) {
- let info = {
- day: String(i - showLastNum + 1),
- month: String(month),
- year: String(year)
- }
- calendar.push(info)
- } else {
- let info = {
- day: String(i - (showLastNum + days) + 1),
- month: String(nextMonth),
- year: String(nextYear)
- }
- calendar.push(info)
- }
- }
- return calendar
- }
- export default getCalendar
|