一年中获得一周

时间:2013-08-28 03:07:19

标签: javascript momentjs

时刻js具有获取一个月内天数的功能:http://momentjs.com/docs/#/displaying/days-in-month/

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

4 个答案:

答案 0 :(得分:11)

在一年的最后一天使用isoWeek获取周数,例如:

function weeksInYear(year) {
   return Math.max(
            moment(new Date(year, 11, 31)).isoWeek()
          , moment(new Date(year, 11, 31-7)).isoWeek()
   );
}

答案 1 :(得分:10)

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

另一种方法是检查返回的年份是否相同,并减去日期数字,直到它为止。

function getWeekNumber(d) {
    // Copy date so don't modify original
    d = new Date(+d);
    d.setHours(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;
}

alert(weeksInYear(2015)); // 53

getWeekNumber 代码来自此处:Get week of year in JavaScript like in PHP

修改

根据Scott的建议,这里有一个没有do循环的建议,所以如果12月31日是在接下来的一年,它将在12月24日获得一周。

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

作为测试,2013-12-31在2014年第1周,weeksInYear(2013)返回52。

答案 2 :(得分:4)

Feb. 4th 2014周岁和年轻人isoWeeksInYear函数被添加到moment.js

所以今天你可以使用moment().isoWeeksInYear()moment().weeksInYear()

有关详情,请参阅docs

答案 3 :(得分:-1)

获取一年中您可能会感兴趣的所有星期和期间

function getWeekPeriodsInYear(year) {
  weeks = [];

  // Get the first and last day of the year
  currentDay = moment([year, 1]).startOf('year');
  dayOfWeek = moment(currentDay).day();
  lastDay = moment([year, 1]).endOf('year');
  weeksInYear = moment(`${year}-01-01`).isoWeeksInYear();
  daysToAdd = 7 - dayOfWeek;

  for (let weekNumber = 1; weekNumber < weeksInYear + 1; weekNumber++) {
    let endOfWeek = moment(currentDay).add(daysToAdd, 'days');
    if (moment(endOfWeek).year() !== year) {
        endOfWeek = lastDay;
    }
    weeks.push({ weekNumber, start: currentDay.toDate(), end: endOfWeek.toDate() });
    currentDay = endOfWeek.add(1, 'day');
    daysToAdd = 6;
}
return weeks;
}

getWeekPeriodsInYear(new Date().getFullYear()).forEach(period =>
  document.write(`Week ${period.weekNumber} from ${moment(period.start).format('DD-MM-YYYY')} up to and including ${moment(period.end).format('DD-MM-YYYY')}<br/>`)
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>