定时任务是每天都需要执行的操作,因此不能使用时间戳判断,时间戳是新建任务当天的时间。
思路:抛弃日期,转化成时间来操作。可以转化成秒来判断,这样可以省去判断时,然后分,然后秒的逻辑。
解决:(文章使用moment来做时间转化)
1.得到以秒计算的时间
getSeconds(val) {
const h = moment(val).get('hours')
const m = moment(val).get('minutes')
const s = moment(val).get('seconds')
return h * 3600 + m * 60 + s
},
此刻的时间:
const nowTime = this.getSeconds() //此刻时间
const start_time = this.getSeconds(this.start_time * 1000) //任务开始时间
const end_time = this.getSeconds(this.end_time * 1000) //任务结束时间
if (nowTime >= end_time) {
//任务结束
this.taskStatus = true
} else {
if (this.start_time > this.end_time) { //跨天任务
//此刻>=开始时间,或者此刻<=结束时间
//例如 23:00-5:00的任务,此时是1点或是23:30都是在任务之内
//即在前一天此刻>=开始,后一天此刻<=结束
this.status = nowTime >= start_time || nowTime <= end_time
} else { //不跨天
//开始<=此刻<=结束时间
this.status = start_time <= nowTime && nowTime <= end_time
}
}