// 中国标准时间format yyyy-mm-dd
const formatTime = (time) => {
let ymd = ''
let mouth = (time.getMonth() + 1) >= 10 ? (time.getMonth() + 1) : ('0' + (time.getMonth() + 1))
let day = time.getDate() >= 10 ? time.getDate() : ('0' + time.getDate())
ymd += time.getFullYear() + '-' // 获取年份。
ymd += mouth + '-' // 获取月份。
ymd += day // 获取日。
return ymd // 返回日期。
}
// js通过开始时间和结束时间计算出中间的所有日期
const getAllDate = (start, end) => {
let dateArr = []
let startArr = start.split('-')
let endArr = end.split('-')
let db = new Date()
db.setUTCFullYear(startArr[0], startArr[1] - 1, startArr[2])
let de = new Date()
de.setUTCFullYear(endArr[0], endArr[1] - 1, endArr[2])
let unixDb = db.getTime()
let unixDe = de.getTime()
let stamp
const oneDay = 24 * 60 * 60 * 1000;
for (stamp = unixDb; stamp <= unixDe;) {
dateArr.push(formatTime(new Date(parseInt(stamp))))
stamp = stamp + oneDay
}
return dateArr
}
// 计算日期区间所有周末
const getAllWeekday = (start, end) => {
let dateArr = []
let startArr = start.split('-')
let endArr = end.split('-')
let db = new Date()
db.setUTCFullYear(startArr[0], startArr[1] - 1, startArr[2])
let de = new Date()
de.setUTCFullYear(endArr[0], endArr[1] - 1, endArr[2])
let unixDb = db.getTime()
let unixDe = de.getTime()
let stamp
const oneDay = 24 * 60 * 60 * 1000;
for (stamp = unixDb; stamp <= unixDe;) {
let curDay = new Date(parseInt(stamp))
if(curDay.getDay()==0||curDay.getDay()==6){
dateArr.push(formatTime(curDay))
}
stamp = stamp + oneDay
}
return dateArr
}
// 使用
console.log(getAllDate('2021-01-01', '2021-03-11'))
网友评论