Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何计算一年总共有多少周? #16

Open
Hongbusi opened this issue Jun 20, 2022 · 0 comments
Open

如何计算一年总共有多少周? #16

Hongbusi opened this issue Jun 20, 2022 · 0 comments
Labels

Comments

@Hongbusi
Copy link
Member

Hongbusi commented Jun 20, 2022

思路

  1. 首先你得知道是不是闰年,也就是一年是 365 还是 366;
  2. 其次你得知道当年 1 月 1 号是周几。假如是周五,一年 365 天把 1 号 2 号 3 号减去,也就是把第一个不到一周的天数减去等于 362;还得知道最后一天是周几。假如是周五,需要把周一到周五减去,也就是 362 - 5 = 357。正常情况 357 这个数计算出来是 7 的倍数。357 / 7 = 51 即为周数。

实现

function isLeapYear(year) {
  if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0)
    return true

  return false
}

function getDay(date) {
  const day = new Date(date).getDay()
  if (day === 0)
    return 7
  return day
}

function getWeeksByYear(year = new Date().getFullYear()) {
  const currentYearDays = isLeapYear(year) ? 366 : 365
  const beforeDays = 7 - getDay(`${year}-01-01`) + 1
  const afterDays = getDay(`${year}-12-31`)

  const weeks = (currentYearDays - beforeDays - afterDays) / 7
  return weeks
}

getWeeksByYear() // 51
getWeeksByYear(2020) // 51

补充

判断是否是闰年的条件(二者满足其中之一即为闰年):

  1. 可以被 4 整除,但不能被 100 整除;
  2. 可以被 400 整除。
@Hongbusi Hongbusi added handwritten-code JS javascript today 每日一题。 and removed today 每日一题。 labels Jun 20, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

No branches or pull requests

1 participant