js判断时间跨度是否超过3个月
前景: vue + iview的datePicker组件 , 需求 选择时间范围不能超过三个月!第一次写博客纪录,参考了几位不同大佬的方法组合写的1.先判断获取每个月有多少天 (含平润年)data: ‘2020-02-27’getMonthDay (date) {let baseMonthsDay = [31,28,31,30,31,30,31,31,30,31,30,31]...
·
前景: vue + iview的datePicker组件 , 需求 选择时间范围不能超过三个月!
第一次写博客纪录,参考了几位不同大佬的方法组合写的
1.先判断获取每个月有多少天 (含平润年)
data: ‘2020-02-27’
// 获取当前月份对应天数
getMonthDay (date) {
const baseMonthsDay = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] // 各月天数
const dataList = date.split('-')
const thisYear = Number(dataList[0]) // 年
const thisMonth = Number(dataList[1]) - 1 // 月
let thisMonthDays = baseMonthsDay[thisMonth] // 当前月对应天数
// 判断是否为闰年
function isRunYear (fullYear) {
// eslint-disable-next-line eqeqeq
return ((fullYear % 4 == 0 && fullYear % 100 != 0) || fullYear % 400 == 0)
}
// 闰年 2月 29天
if (isRunYear(thisYear) && thisMonth === 1) {
thisMonthDays = thisMonthDays + 1
}
return thisMonthDays
},
- 根据选择开始时间-结束时间的毫秒差是否小于三个月的毫秒数
timeBetween (startDate, endDate) {
let start = new Date(startDate.replace(/-/g,"/")).getTime();
let end = new Date(endDate.replace(/-/g,"/")).getTime();
let betweenTime = startDate.split('-')
if (betweenTime[1] === '12') { // 开始日期往后一个月 作为中间月
betweenTime[1] = '01' // startDate是12月,下个月是1月
betweenTime[0] = betweenTime[0] - 0 + 1
} else if ((betweenTime[1] - 0 + 1) < 10) {
betweenTime[1] = '0' + (betweenTime[1] - 0 + 1) // 补0
} else {
betweenTime[1] = betweenTime[1] - 0 + 1
}
betweenTime = betweenTime.join('-')
let lastTime = betweenTime.split('-')
if (lastTime[1] === '12') { // 开始日期往后一个月 作为中间月
lastTime[1] = '01'
lastTime[0] = lastTime[0] - 0 + 1
} else if ((lastTime[1] - 0 + 1) < 10) {
lastTime[1] = '0' + (lastTime[1] - 0 + 1)
} else {
lastTime[1] = lastTime[1] - 0 + 1
}
lastTime = lastTime.join('-')
let n = this.getMonthDay(startDate) + this.getMonthDay(lastTime) + this.getMonthDay(betweenTime)
// 判断毫秒数如果大于90天返回true 即超过90天 反之 false
return end - start + (n * 24 * 60 * 60 * 1000) > n * 24 * 60 * 60 * 1000 ? true : false
},
- 需要调用的地方调用即可,记得传入字符串类型 ‘yyyy-mm-dd’
刚写好的,热fufu的呢。如有不足,请不吝指教!!!
附上参考链接:
https://blog.csdn.net/amyloverice/article/details/79385669
https://blog.csdn.net/tangcc110/article/details/79188224
https://bbs.csdn.net/topics/390583370 // 剑神一笑的评论
更多推荐
已为社区贡献2条内容
所有评论(0)