获得一年中的周数 [英] Get weeks in year

查看:65
本文介绍了获得一年中的周数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Moment js 有一个获取一个月天数的函数:http://momentjs.com/docs/#/displaying/days-in-month/

Moment js has a function to get the number of days in a month : http://momentjs.com/docs/#/displaying/days-in-month/

但是我找不到一个函数来查找一年中的 iso 周数(52 或 53).

However I could not find a function to find the number of iso weeks in a year (52 or 53).

推荐答案

这是一个不依赖于库的答案.它使用一个函数来计算所需年份的 12 月 31 日所在的那一周.如果周为 1(即 12 月 31 日在下一年的第一周),它会将天数向下移动,直到获得不同的值,这将是所需年份的最后一周.

Here's an answer that isn't dependent on a library. It uses a function to calculate the week in the year that 31 December falls in for the required year. If the week is 1 (i.e. 31 December is in the first week of the following year), it moves the day number lower until it gets a different value, which will be the last week of the required year.

function getWeekNumber(d) {
  // Copy date so don't modify original
  d = new Date(+d);
  d.setHours(0, 0, 0, 0);
  // Set to nearest Thursday: current date + 4 - current day number
  // Make Sunday's day number 7
  d.setDate(d.getDate() + 4 - (d.getDay() || 7));
  // Get first day of year
  var yearStart = new Date(d.getFullYear(), 0, 1);
  // Calculate full weeks to nearest Thursday
  var weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7)
  // Return array of year and week number
  return [d.getFullYear(), weekNo];
}

function weeksInYear(year) {
  var month = 11,
    day = 31,
    week;

  // Find week that 31 Dec is in. If is first week, reduce date until
  // get previous week.
  do {
    d = new Date(year, month, day--);
    week = getWeekNumber(d)[1];
  } while (week == 1);

  return week;
}

[2015, 2016, 2029, new Date().getFullYear()].forEach(year =>
  console.log(`${year} has ${weeksInYear(year)} weeks`)
);

getWeekNumber 代码来自此处:像在 PHP 中一样在 JavaScript 中获取一年中的一周.

或者,如果 12 月 31 日在下一年的第 1 周,则主题年有 52 周,否则有 53 周.

Alternatively, if 31 December is in week 1 of the following year, then the subject year has 52 weeks and otherwise has 53 weeks.

function getWeekNumber(d) {
  d = new Date(+d);
  d.setHours(0, 0, 0, 0);
  d.setDate(d.getDate() + 4 - (d.getDay() || 7));
  var yearStart = new Date(d.getFullYear(), 0, 1);
  var weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7)
  return [d.getFullYear(), weekNo];
}

function weeksInYear(year) {
  var d = new Date(year, 11, 31);
  var week = getWeekNumber(d)[1];
  return week == 1 ? 52 : week;
}

[2015, 2016, 2029, new Date().getFullYear()].forEach(year =>
  console.log(`${year} has ${weeksInYear(year)} weeks`)
);

这篇关于获得一年中的周数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆