废话少说上代码
首先我们先写一段可以用于格式化时间的代码:格式为yy-mm-dd
// 格式化时间
formatTime(time) {
const timer = new Date(time)
const year = timer.getFullYear()
const mouth = timer.getMonth() + 1 > 10 ? timer.getMonth() + 1 : '0' + (timer.getMonth() + 1)
const date = timer.getDate() > 10 ? timer.getDate() : '0' + timer.getDate()
return year + '-' + mouth + '-' + date
},
我们还需要一个传入年份和月份,返回给我们这个月有多少天的方法
lastDay(Year, Moon) {
return new Date(Year, Moon, 0).getDate()
},
之后我们编写获取时间的代码,并将其保存起来,当页面进入时,在create()中调用
getTime() {
this.now = new Date() // 当前日期
this.nowDay = this.now.getDate() // 当前日
this.nowDayOfWeek = this.now.getDay() // 今天本周的第几天
this.nowMonth = this.now.getMonth() // 当前月
this.nowYear = this.now.getFullYear() // 当前年
},
然后获取本周的时间段
// 获得本周的开端日期
getWeekStartDate(nowDay, nowMonth, nowYear, nowDayOfWeek) {
const weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1)
return this.formatTime(weekStartDate)
},
// 获得本周的停止日期
getWeekEndDate(nowDay, nowMonth, nowYear, nowDayOfWeek) {
const weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek + 1))
return this.formatTime(weekEndDate)
}
获取本月的时间段
// 获得本月的开端日期
getMonthStartDate(nowYear, nowMonth) {
const monthStartDate = new Date(nowYear, nowMonth, 1)
return this.formatTime(monthStartDate)
},
// 获得本月的停止日期
getMonthEndDate(nowYear, nowMonth) {
const monthEndDate = new Date(nowYear, nowMonth, this.lastDay(this.nowYear, this.nowMonth) - 1)
return this.formatTime(monthEndDate)
}
获取年的时间段
// 获得本年的开端日期
getYearStartDate(nowYear) {
const YearStartDate = new Date(nowYear, 0, 1)
return this.formatTime(YearStartDate)
},
// 获得本年的开端日期
getYearEndDate(nowYear) {
const YearStartDate = new Date(nowYear, 11, 31)
return this.formatTime(YearStartDate)
}
完事!