为什么加1?

我从https://gist.github.com/vincentorback/8edffeca20e7a9e5e2a6那里获得了这段代码,并且想知道一些有关它的信息。

/**
 * Gets the ISO week number for a given date.
 * @param d either Date or number,the date to get week number for.
 * @returns The ISO week number for given date.
 */
function getWeekNumber(d: any) {
    // copy given date
    d = new Date(+d);
    d.setHours(0,0);
    // Set date to nearest thursday
    // If getDay is 0 it's sunday,we change the day number to 7 making it the last day of the week
    d.setDate(d.getDate() + 4 - (d.getDay() || 7));
    const yearStart: any = new Date(d.getFullYear(),1);
    // First calculate delta of start of year and given date in milliseconds: (d - yearStart)
    // Then we divide that by 86.400.000 ((d - yearStart) / 1000 / 60 / 60 / 24 ) to know difference in days
    // Then we calculate the number of weeks
    return Math.ceil((((d - yearStart) / 86400000) + 1) / 7); // <-- why + 1?
}

我真的不明白为什么在这里做+ 1。还有,为什么星期天将天数更改为7?

我试图评论我确实发现的事情,但是如果仍然不清楚,请告诉我!

sky03191 回答:为什么加1?

// Set date to nearest thursday
// If getDay is 0 it's sunday,we change the day number to 7 making it the last day of the week
d.setDate(d.getDate() + 4 - (d.getDay() || 7));

在此阶段,d是纯日期。 d.getDay()共有7种可能值,分别对应于星期几:0代表星期日,1代表星期一,依此类推。

正如评论所指出的,|| 7意味着我们现在星期一有1,...星期天有7

对于任何日期,如果我们减去它的星期几号(在此系统中),则会得到它之前的星期天(尝试一下!)。例如,今天是2019年11月5日,星期二。星期几是2。今天减去2天是今天之前的星期日。

然后我们添加4,这表示我们可以根据需要在星期四。由于0-> 7映射,这是“最近”的星期四。如果不将星期日的0映射为7,则2019年11月3日星期日将结束为星期7日;带有该映射的 结束于10月31日(星期四)。


// First calculate delta of start of year and given date in milliseconds: (d - yearStart)
// Then we divide that by 86.400.000 ((d - yearStart) / 1000 / 60 / 60 / 24 ) to know difference in days
// Then we calculate the number of weeks
return Math.ceil((((d - yearStart) / 86400000) + 1) / 7); // <-- why + 1?

此时d是纯日期星期四,而yearStart是同年1月1日。

从日期中减去日期,得出的差值为毫秒。一天有86400000毫秒,因此将daet减值除以86400000可以得出天数的差值。

所以((d - yearStart) / 86400000)是一年中的第一天,从0开始,直到1月1日。

我们希望获得一年中的一周的值,因此我们将其除以7,这在大多数情况下会给我们一个非整数,但我们想要一个整数,以便取最大数(即,向上取整)

但是,这意味着1月1日(每年的第0天)将作为第0周中的唯一一天结束。显然,我们不希望这样做,因此我们将第1天添加为年。

所以(((d - yearStart) / 86400000) + 1)是一年中的第一天,从1月1日的 1 开始。

我们现在在一年中的每一天都有数字1到365(或366);除以7并四舍五入以得出一年中各个星期的数字1到53。

本文链接:https://www.f2er.com/3160783.html

大家都在问