/*
//api
num : year
num : month
num : date
num : day
num : time
data: getData()
data: preMonth()
data: nextMonth()
data: preYear()
data: nextYear()
data: thisMonth()
data: costomDate()
data{isToday,isThisMonth,date}
*/
export default function Calendar(studyWeek) {
var calendar = new Object()
//日期数据基础
calendar.baseDate = new Date()
//初始化
calendar.init = function () {
this.year = this.baseDate.getFullYear()
this.month = this.baseDate.getMonth()
}
calendar.init()
//获取数据
calendar.getData = function () {
var data = []
//起始值
var date = new Date(this.year, this.month, 1)
if (date.getDay() === 0) {
date.setTime(date.getTime() - 86400000 * 6)
} else {
date.setTime(date.getTime() - 86400000 * (date.getDay() - 1))
}
do {
for (var i = 0; i < 7; i++) {
var obj = {}
obj.isThisMonth = date.getMonth() == this.month ? true : false
obj.isToday = date.getDate() == new Date().getDate() && date.getMonth() == new Date().getMonth() && date.getFullYear() == new Date().getFullYear() ? true : false
obj.isWeek = i == 0 || i == 6 ? true : false
obj.date = date.getDate() > 9 ? date.getDate() : '0' + date.getDate()
obj.month = (date.getMonth() + 1) > 9 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1)
obj.year = date.getFullYear()
// obj.weekNum = this.setWeekNum(obj)
data.push(obj)
date.setTime(date.getTime() + 86400000)
}
} while (date.getMonth() == this.month || data.length < 42)
return data
}
//设置周次
calendar.setWeekNum = function (obj) {
var study = new Date(studyWeek.year, studyWeek.month, studyWeek.date).getTime()
var now = new Date(obj.year, obj.month, obj.date).getTime()
var weekNum = Math.ceil((now - study) / (1000 * 60 * 60 * 24) / 7)
return weekNum + 1
}
//上月
calendar.preMonth = function () {
this.month--
this.baseDate.setMonth(this.month, 1)
this.init()
return this.getData()
}
//下月
calendar.nextMonth = function () {
this.month++
this.baseDate.setMonth(this.month, 1)
this.init()
return this.getData()
}
//上一年
calendar.preYear = function () {
this.year -= 1
this.baseDate.setFullYear(this.year)
this.init()
return this.getData()
}
//下一年
calendar.nextYear = function () {
this.year += 1
this.baseDate.setFullYear(this.year)
this.init()
return this.getData()
}
//本月
calendar.thisMonth = function () {
this.baseDate = new Date()
this.init()
return this.getData()
}
//自定义年月
calendar.customDate = function (year, month) {
this.year = +year
this.month = +month
this.baseDate.setFullYear(this.year)
this.baseDate.setMonth(this.month - 1, 1)
this.init()
return this.getData()
}
//返回值
return calendar
}
使用:
var calendar = new Calendar(); var data = calendar.getData();
根据获取的data进行自由渲染。