如何计算当前连续天数(从当前日期开始连续几天)


const arr = [
{
"date": "2019-09-18"
},
{
"date": "2019-09-19"
},
{
"date": "2019-09-21"
},
{
"date": "2019-09-22"
},
{
"date": "2019-09-23"
}
]
function currentStreak(arr) {
let count = 0
arr.reverse().forEach((el, i) => {
if (new Date() - new Date(el.date) === i * 86400000) count++
})
return count
}

我很难把它发挥作用。假设当前日期为"2019-09-23",为什么上面的代码返回0,而它应该返回3

您正在传递当前日期,即今天的日期-11月5日星期二因此计算是基于今天的日期进行的,您必须传递日期对象的值

例如:-

const arr = [
{
"date": "2019-09-18"
},
{
"date": "2019-09-19"
},
{
"date": "2019-09-21"
},
{
"date": "2019-09-22"
},
{
"date": "2019-09-23"
}
]
function currentStreak(arr) {
let count = 0
arr.reverse().forEach((el, i) => {
if (new Date('2019-09-23') - new Date(el.date) === i * 86400000) count++
})
return count;
}
console.log(currentStreak(arr))

由于new Date((提供的是日期+当前时间,因此它无法与午夜提供时间的new Date(YYYY-MM-DD(进行正确比较。

如果你将日期修改为午夜,那么它将正确比较。所以你的代码会是这样的。

function currentStreak(arr) {
let count = 0
arr.reverse().forEach((el, i) => {
if ((new Date().setUTCHours(0,0,0,0) - new Date(el.date).setUTCHours(0,0,0,0)) === i * 86400000) count++
})
return count
} 

new Date()返回此-Tue Nov 05 2019 15:16:22 GMT+0800 (Singapore Standard Time)

所以在你的if条件下,它不会增加。更改new Date()的格式,并将其与您的数组进行比较。

const arr = [
{
"date": "2019-09-18"
},
{
"date": "2019-09-19"
},
{
"date": "2019-09-21"
},
{
"date": "2019-09-22"
},
{
"date": "2019-09-23"
}
]
function currentStreak(arr) {
let count = 0
arr.reverse().forEach((el, i) => {
if ((new Date() - new Date(el.date) >= i * 86400000) && (new Date() - new Date(el.date) < (i+1) * 86400000))  count++
})
return count
}
console.log(currentStreak(arr));

它不起作用,因为你没有包括分钟、小时、秒和毫秒。

最新更新