javascript 获取一年中的周数

6jjcrrmo  于 2022-12-25  发布在  Java
关注(0)|答案(5)|浏览(291)

Moment js有一个函数可以得到一个月的天数:http://momentjs.com/docs/#/displaying/days-in-month/
然而,我找不到一个函数来查找一年中ISO周数(52或53)。

ruarlubt

ruarlubt1#

这里有一个不依赖于库的答案,它使用一个函数来计算12月31日在所需年份中的星期,如果星期是1(即12月31日是下一年的第一周),它会将日期编号向下移动,直到得到一个不同的值,这将是所需年份的最后一周。

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 * 代码来自此处:在JavaScript中获取一年中的星期,就像在PHP中一样。

编辑

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

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`)
);
zwghvu4y

zwghvu4y2#

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

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

sigwle7e3#

Feb. 4th 2014将weeksInYear和isoWeeksInYear函数添加到moment.js中
今天你可以用moment().isoWeeksInYear()或者moment().weeksInYear()
有关详细信息,请参阅文档

xam8gpfp

xam8gpfp4#

我想我会发布一个简单得多的版本,我从维基百科的文章。
文章中的表述是:
“某一年的周数等于12月28日的相应周数,因为它是唯一一个总是在该年最后一周的日期,因为它是1月4日之前的一周,而1月4日总是在下一年的第一周。
仅使用序数y,该年的周数可由函数确定,该函数返回12月31日是星期几。
因此,getWeekFor(new Date(2022, 11, 28)将year替换为您想要的任何年份,将始终为您提供该年份的周数。

// modified from https://stackoverflow.com/questions/6117814/get-week-of-year-in-javascript-like-in-php 
const getWeekFor = (date) => {
    const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
    const dayNum = d.getUTCDay() || 7;
    const utc = new Date(d.setUTCDate(d.getUTCDate() + 4 - dayNum));
    const yearStart = new Date(Date.UTC(utc.getUTCFullYear(), 0, 1)).getTime();
    return Math.ceil(((d.getTime() - yearStart) / 86400000 + 1) / 7);
};

const weeks = getWeekFor(new Date(2020, 11, 28)) // 53.
console.log(weeks);
0sgqnhkj

0sgqnhkj5#

获取一年中该周的所有周和时段,供可能感兴趣的人使用

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>

相关问题