获取当前日期或者某个日期相隔N天内的全部日期以及星期几
业务需要需要获取当前日期相隔30天内的全部日期以及星期几,没插件因此特地写了一个:
/* 说明:获取当前日期或者某个日期相隔N天内的全部日期以及星期几 使用: let test = new getdiffdate(2, '2019-08-08') console.log(test.getdiffdate()); */ class Getdiffdate { /** * @param {Number} n //必传,相隔多少天 * @param {String} stime //可选,开始日期,如2019-08-08,不传则为当前时间 */ constructor(n, stime) { this.n = n this.stime = stime } getdiffdate () { let weekArray = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"] let i = 0 //数组key值 let diffdate = [] //存放时间数组 let week = '' //当前星期几 // 开始时间 let stime_date = this.stime ? new Date(this.stime) : new Date() let stime_stamp = stime_date.getTime() week = weekArray[stime_date.getDay()] // 结束时间 let etime_date = new Date(stime_date) etime_date.setDate(stime_date.getDate() + this.n) let etime_stamp = new Date(etime_date).getTime() //未设置开始时间,格式化当前时间 if (!this.stime) { this.stime = this._getdate(stime_date) } //开始日期小于等于结束日期,并循环 while (stime_stamp <= etime_stamp) { let day_obj = { date: this.stime, week: week } diffdate[i] = day_obj; //增加一天时间戳后的日期 let next_date = stime_stamp + (24 * 60 * 60 * 1000); let next_date_obj = new Date(next_date) this.stime = this._getdate(next_date_obj) week = weekArray[next_date_obj.getDay()] i++; stime_stamp = next_date } return diffdate } // 格式化时间 _getdate (date) { let etime_date_y = date.getFullYear() + '-'; let etime_date_m = (date.getMonth() + 1 < 10) ? '0' + (date.getMonth() + 1) + '-' : (date.getMonth() + 1) + '-'; let etime_date_d = (date.getDate() < 10) ? '0' + date.getDate() : date.getDate(); let fomatterdate = etime_date_y + etime_date_m + etime_date_d return fomatterdate } } export default Getdiffdate