参考博文:https://blog.youkuaiyun.com/qq_36742720/article/details/82455061
前两天要画一个echarts图,通过点击 上一周 本周 和 下一周 的按钮来不断获取图的数据。
在网上找了蛮久,发现了这个博主写的,超级棒,我改了一下,写在vue里,以便以后用到。
// 获取 上周、本周和下周 的时间
getDates(date) {
var year = date.getFullYear() + '-'
var month = ((date.getMonth() + 1) + '-').length === 2 ? ('0' + (date.getMonth() + 1) + '-') : (date.getMonth() + 1) + '-'
var day = (date.getDate() + '').length === 1 ? ('0' + date.getDate()) : date.getDate()
this.timeStamp.push(year + month + day)
return year + month + day
},
addDate(date, n) {
date.setDate(date.getDate() + n)
return date
},
setDate(date) {
this.timeStamp = []
var week = date.getDay() - 1
date = this.addDate(date, week * -1)
this.currentFirstDate = new Date(date)
for (var i = 0; i < 7; i++) {
this.getDates(i === 0 ? date : this.addDate(date, 1)) // 星期一开始
}
},
// 点击上一周
lastWeek() {
this.setDate(this.addDate(this.currentFirstDate, -7))
this.getGraphChartData(this.timeStamp[0], this.timeStamp[6])
},
// 本周
onWeek() {
this.setDate(this.addDate(new Date(), -1))
this.getGraphChartData(this.timeStamp[0], this.timeStamp[6])
},
// 下一周
nextWeek() {
this.setDate(this.addDate(this.currentFirstDate, 7))
this.getGraphChartData(this.timeStamp[0], this.timeStamp[6])
},
写在return里的定义:
// 点击上周下周按钮的初始时间
currentFirstDate: new Date(),
// 返回一周时间的集合
timeStamp: []
此外,还有根据某一时间计算前五分钟、后几分钟的方法:
// startTime是标准时间格式,ex:2019-04-23 00:00:00
var date = new Date(startTime.replace(/-/g, '/'))
// 标准时间转换成时间戳
var time = date.getTime()
// 计算前五分钟
var time1 = time - 1000 * 60 * 5
// 计算后十五分钟
var time2 = time + 1000 * 60 * 15
// 时间戳转换成标准时间
var date1 = this.getTime(time1)
var date2 = this.getTime(time2)
转标准时间的 this.getTime方法:
// 更改时间格式
export function getTime(date) {
var dateStr = ''
date = new Date(date)
var yy = date.getFullYear()
var mm = parseInt(date.getMonth()) + 1
var dd = parseInt(date.getDate())
var hh = date.getHours()
var min = date.getMinutes()
var ss = date.getSeconds()
if (mm < 10) {
mm = '0' + mm
}
if (dd < 10) {
dd = '0' + dd
}
if (hh < 10) {
hh = '0' + hh
}
if (min < 10) {
min = '0' + min
}
if (ss < 10) {
ss = '0' + ss
}
dateStr = yy.toString() + '-' + mm + '-' + dd + ' ' + hh + ':' + min + ':' + ss
return dateStr
}
总结完毕。