js/vue/angular獲取日歷的方法
getDates(d, t = 0) { var curDate = new Date(d.replace(/-/g, '/')) var curMonth = curDate.getMonth() curDate.setMonth(curMonth + t + 1) curDate.setDate(0) var curDates = new Array(curDate.getDate()).fill(0).map((item, key) => { return key + 1 }) return curDates } getWeek(d) { var curDate = new Date(d.replace(/-/g, '/')) curDate.setDate(1) return curDate.getDay() } getFullChunkDates(d) { var curDates: any = this.getDates(d) var preDates: any = this.getDates(d, -1) var nexDates: any = this.getDates(d, 1) var curWeek: any = this.getWeek(d) curDates = curDates.map((i, k) => { return { num: i, fullDate: /(^\d{4})-(\d{1,2})-/.exec(d)[0] + i, show: 1 } }) preDates = preDates.map(i => { return { num: i, show: 0 } }) nexDates = nexDates.map(i => { return { num: i, show: 0 } }) var preCurDates = preDates.slice(preDates.length - (curWeek === 0 ? 6 : curWeek - 1), preDates.length).concat(curDates) return preCurDates.concat(nexDates.slice(0, 42 - preCurDates.length)) }
this.days = this.getFullChunkDates('2019-10-16')
//一二三四五六日
<div class="c-day"> <div class="d-item" *ngFor="let item of days"> <div>{{item.num}}</div> </div> </div>
.c-day{ display: flex; width: 700px; flex-wrap: wrap; justify-content: space-around; } .d-item{ display: flex; display: inline-block; width: 100px; box-sizing: border-box; border: 1px solid #ccc; text-align: center; padding: 40px; }
另外一種方法:日一二三四五六
const y = this.year, m = this.month let d = new Date() // 本月第一天 , firstDayOfMonth = new Date(y, m, 1).getDay() // 本月最后一天 , lastDateOfMonth = new Date(y, m + 1, 0).getDate() // 上個月最后一天 , lastDayOfPreMonth = m === 0 ? new Date(y - 1, 11, 0).getDate() : new Date(y, m, 0).getDate() let week = [] // 月第一=幾天 let i = 1 do { let dow = new Date(y, m, i).getDay() // 周日則單獨一行 if(dow === 0) { week = [] } // 每月第一天關於上個月尾數幾天當月顯示處理 else if(i === 1) { let k = lastDayOfPreMonth - firstDayOfMonth + 1 for(let j = 0; j < firstDayOfMonth; j++) { let obj = { label: k, } week.push(obj) k++ } } // 查詢當天,高亮處理 let chk = new Date() let chkY = chk.getFullYear() let chkM = chk.getMonth() if(chkY === this.year && chkM === this.month && i === this.day) { week.push({ label: i, // 本月 current: true, today: true, }) // 其他本月常規天 } else { week.push({ label: i, // 本月 current: true, }) } // 周六則閉合 if(dow === 6) { this.weeks.push(week) } // 本月最后一天,處理下個月首幾日在當月內顯示 else if(i === lastDateOfMonth) { let k = 1 for(dow; dow < 6; dow++) { let obj = { label: k, } week.push(obj) k++ } this.weeks.push(week) } i++ } while(i <= lastDateOfMonth)