javascript JS 获得一个月的周数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28384869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:53:16  来源:igfitidea点击:

moment JS get number of weeks in a month

javascriptmomentjs

提问by h_a86

I am trying to calculate number of weeks in a month using moment js. But I am getting wrong results for some months like May 2015 and August 2015.

我正在尝试使用 moment js 计算一个月中的周数。但是我在 2015 年 5 月和 2015 年 8 月这样的几个月里得到了错误的结果。

I am using this code.

我正在使用此代码。

var start = moment().startOf('month').format('DD');
var end = moment().endOf('month').format('DD');
var weeks = (end-start+1)/7;
weeks = Math.ceil(weeks);

Is there any prebuilt method in moment JS for getting number of weeks.

在 moment JS 中是否有任何预构建的方法来获取周数。

回答by guillaumepiot

I have created this gist that finds all the weeks in a given month and year. By calculated the length of calendar, you will know the number of weeks.

我创建了这个 gist,它可以找到给定月份和年份中的所有周。通过计算 的长度calendar,您将知道周数。

https://gist.github.com/guillaumepiot/095b5e02b4ca22680a50

https://gist.github.com/guillaumepiot/095b5e02b4ca22680a50

# year and month are variables
year = 2015
month = 7 # August (0 indexed)
startDate = moment([year, month])

# Get the first and last day of the month
firstDay = moment(startDate).startOf('month')
endDay = moment(startDate).endOf('month')

# Create a range for the month we can iterate through
monthRange = moment.range(firstDay, endDay)

# Get all the weeks during the current month
weeks = []
monthRange.by('days', (moment)->
    if moment.week() not in weeks
        weeks.push(moment.week())
)

# Create a range for each week
calendar = []
for week in weeks
    # Create a range for that week between 1st and 7th day
    firstWeekDay = moment().week(week).day(1)
    lastWeekDay = moment().week(week).day(7)
    weekRange = moment.range(firstWeekDay, lastWeekDay)

    # Add to the calendar
    calendar.push(weekRange)

console.log calendar

回答by Noor

Can be easily done using raw javascript:

可以使用原始 javascript 轻松完成:

function getNumWeeksForMonth(year,month){
              date = new Date(year,month-1,1);
              day = date.getDay();
              numDaysInMonth = new Date(year, month, 0).getDate();
              return Math.ceil((numDaysInMonth + day) / 7);
}

You get the day index of the first day, add it to the number of days to compensate for the number of days lost in the first week, divide by 7 and use ceil to add 1 for the simplest overflow in the next week

你得到第一天的天数索引,把它加到天数上来补偿第一周损失的天数,除以7,然后用ceil加1为下周最简单的溢出

回答by jonruna

EDIT:

编辑:

NEW and hopefully very correct implementation:

新的,希望非常正确的实现:

function calcWeeksInMonth(date: Moment) {
  const dateFirst = moment(date).date(1);
  const dateLast = moment(date).date(date.daysInMonth());
  const startWeek = dateFirst.isoWeek();
  const endWeek = dateLast.isoWeek();

  if (endWeek < startWeek) {
    // Yearly overlaps, month is either DEC or JAN
    if (dateFirst.month() === 0) {
      // January
      return endWeek + 1;
    } else {
      // December
      if (dateLast.isoWeekday() === 7) {
        // Sunday is last day of year
        return endWeek - startWeek + 1;
      } else {
        // Sunday is NOT last day of year
        return dateFirst.isoWeeksInYear() - startWeek + 1;
      }
    }
  } else {
    return endWeek - startWeek + 1;
  }
}

Outputs the following values for the following dates:

输出以下日期的以下值:

calcWeeksInMonth(moment("2016-12-01")); // 5

calcWeeksInMonth(moment("2017-01-01")); // 6
calcWeeksInMonth(moment("2017-02-01")); // 5
calcWeeksInMonth(moment("2017-03-01")); // 5
calcWeeksInMonth(moment("2017-04-01")); // 5
calcWeeksInMonth(moment("2017-05-01")); // 5
calcWeeksInMonth(moment("2017-06-01")); // 5
calcWeeksInMonth(moment("2017-07-01")); // 6
calcWeeksInMonth(moment("2017-08-01")); // 5
calcWeeksInMonth(moment("2017-09-01")); // 5
calcWeeksInMonth(moment("2017-10-01")); // 6
calcWeeksInMonth(moment("2017-11-01")); // 5
calcWeeksInMonth(moment("2017-12-01")); // 5

calcWeeksInMonth(moment("2018-01-01")); // 5


OLD and very incorrect implementation:

旧且非常不正确的实现:

calcWeeksInMonth(date) {
    const dateFirst = moment(date).date(1)
    const dateLast = moment(date).date(date.daysInMonth())
    const startWeek = dateFirst.week()
    const endWeek = dateLast.week()
    if (endWeek < startWeek) {
        return dateFirst.weeksInYear() - startWeek + 1 + endWeek
    } else {
        return endWeek - startWeek + 1
    }
}

This seems to output correct results, feedback welcome if there is something I missed!

这似乎输出了正确的结果,如果我错过了什么,欢迎反馈!

回答by Kanish Mathew

It display the list of weeks in a month with 'moment.js'.
It has been written in typescript with angular 6+.

它使用“moment.js”显示一个月中的周数列表。
它是用 angular 6+ 的打字稿编写的。

Install moment with 'npm i moment'

使用“npm i moment”安装 moment

Inside the ts file.

在 ts 文件中。

weeks_in_month() {
    let year = 2019;  // change year
    let month = 4; // change month here
    let startDate = moment([year, month - 1])
    let endDate = moment(startDate).endOf('month');

    var dates = [];
    var weeks = [];

    var per_week = [];
    var difference = endDate.diff(startDate, 'days');

    per_week.push(startDate.toDate())
    let index = 0;
    let last_week = false;
    while (startDate.add(1, 'days').diff(endDate) < 0) {
      if (startDate.day() != 0) {
        per_week.push(startDate.toDate())
      }
      else {
        if ((startDate.clone().add(7, 'days').month() == (month - 1))) {
          weeks.push(per_week)
          per_week = []
          per_week.push(startDate.toDate())
        }
        else if (Math.abs(index - difference) > 0) {
          if (!last_week) {
            weeks.push(per_week);
            per_week = [];
          }
          last_week = true;
          per_week.push(startDate.toDate());
        }
      }
      index += 1;
      if ((last_week == true && Math.abs(index - difference) == 0) ||
        (Math.abs(index - difference) == 0 && per_week.length == 1)) {
        weeks.push(per_week)
      }
      dates.push(startDate.clone().toDate());
    }
    console.log(weeks);
}

Result:

结果:

Array of date moments.

日期时刻数组。

[Array(6), Array(7), Array(7), Array(7), Array(3)]

0: (6) [Mon Apr 01 2019 00:00:00 GMT+0530 (India Standard Time),  
Tue Apr 02 2019 00:00:00 GMT+0530 (India Standard Time),  
Wed Apr 03 2019 00:00:00 GMT+0530 (India Standard Time),  
Thu Apr 04 2019 00:00:00 GMT+0530 (India Standard Time),  
Fri Apr 05 2019 00:00:00 GMT+0530 (India Standard Time),  
Sat Apr 06 2019 00:00:00 GMT+0530 (India Standard Time)]

1: (7) [Sun Apr 07 2019 00:00:00 GMT+0530 (India Standard Time),  
Mon Apr 08 2019 00:00:00 GMT+0530 (India Standard Time),  
Tue Apr 09 2019 00:00:00 GMT+0530 (India Standard Time),  
Wed Apr 10 2019 00:00:00 GMT+0530 (India Standard Time),  
Thu Apr 11 2019 00:00:00 GMT+0530 (India Standard Time),  
Fri Apr 12 2019 00:00:00 GMT+0530 (India Standard Time),  
Sat Apr 13 2019 00:00:00 GMT+0530 (India Standard Time)]

2: (7) [Sun Apr 14 2019 00:00:00 GMT+0530 (India Standard Time),  
Mon Apr 15 2019 00:00:00 GMT+0530 (India Standard Time),  
Tue Apr 16 2019 00:00:00 GMT+0530 (India Standard Time),  
Wed Apr 17 2019 00:00:00 GMT+0530 (India Standard Time),  
Thu Apr 18 2019 00:00:00 GMT+0530 (India Standard Time),  
Fri Apr 19 2019 00:00:00 GMT+0530 (India Standard Time),  
Sat Apr 20 2019 00:00:00 GMT+0530 (India Standard Time)]

3: (7) [Sun Apr 21 2019 00:00:00 GMT+0530 (India Standard Time),  
Mon Apr 22 2019 00:00:00 GMT+0530 (India Standard Time),  
Tue Apr 23 2019 00:00:00 GMT+0530 (India Standard Time),  
Wed Apr 24 2019 00:00:00 GMT+0530 (India Standard Time),  
Thu Apr 25 2019 00:00:00 GMT+0530 (India Standard Time),  
Fri Apr 26 2019 00:00:00 GMT+0530 (India Standard Time),  
Sat Apr 27 2019 00:00:00 GMT+0530 (India Standard Time)]

4: (3) [Sun Apr 28 2019 00:00:00 GMT+0530 (India Standard Time),  
Mon Apr 29 2019 00:00:00 GMT+0530 (India Standard Time),  
Tue Apr 30 2019 00:00:00 GMT+0530 (India Standard Time)]

回答by JVitela


function getWeekNums(momentObj) {
    var clonedMoment = moment(momentObj), first, last;

    // get week number for first day of month
    first = clonedMoment.startOf('month').week();
    // get week number for last day of month
    last = clonedMoment.endOf('month').week();

    // In case last week is in next year
    if( first > last) {
        last = first + last;
    }
    return last - first + 1;
}

回答by Erik

Here is a simple way of doing it (based on a solution posted above):

这是一个简单的方法(基于上面发布的解决方案):

const calcWeeksInMonth = (momentDate) => {
  const dateFirst = moment(momentDate).date(1)
  const dateLast = moment(momentDate).date(momentDate.daysInMonth())
  const startWeek = dateFirst.isoWeek()
  const endWeek = dateLast.isoWeek()

  if (endWeek < startWeek) {
    // cater to end of year (dec/jan)
    return dateFirst.weeksInYear() - startWeek + 1 + endWeek
  } else {
    return endWeek - startWeek + 1
  }
}

As far as I can tell, it works correctly for any date thrown at it, but feedback is always welcome!

据我所知,它适用于任何抛出的日期,但始终欢迎反馈!

回答by Ian Buss

Throwing this into the mix

把这个扔进去

import moment from "moment";
export const calcWeeksInMonth = date => {
  let weekMonthEnds = moment(date)
    .date(moment(date).daysInMonth())
    .week();
  let weekMonthStarts = moment(date)
    .date(1)
    .week();

  return weekMonthEnds < weekMonthStarts
    ? 52 - weekMonthStarts + 1
    : weekMonthEnds - weekMonthStarts + 1;
};

回答by Mohit Bhasi

This is the best way out , works well

这是最好的出路,效果很好

moment.relativeTime.dd = function (number) {
    // round to the closest number of weeks
    var weeks = Math.round(number / 7);
    if (number < 7) {
        // if less than a week, use days
        return number + " days";
    } else {
        // pluralize weeks
        return weeks + " week" + (weeks === 1 ? "" : "s"); 
    }
}

Source:How to get duration in weeks with Moment.js?

资料来源:如何使用 Moment.js 获得以周为单位的持续时间?

回答by Bigtrizzy

I have not seen a solution that works in all circumstances. I tried all of these but they all are flawed in one way or another. Ditto with several moment.js github threads. This was my crack at it:

我还没有看到适用于所有情况的解决方案。我尝试了所有这些,但它们都以一种或另一种方式存在缺陷。同上有几个 moment.js github 线程。这是我的破解:

getNumberOfWeeksInMonth = (momentDate) => {
  const monthStartWeekNumber = momentDate.startOf('month').week();

  const distinctWeeks = {
    [monthStartWeekNumber]: true
  };

  let startOfMonth = momentDate.clone().startOf('month');
  let endOfMonth = momentDate.clone().endOf('month');

  //  this is an 'inclusive' range -> iterates through all days of a month
  for (let day = startOfMonth.clone(); !day.isAfter(endOfMonth); day.add(1, 'days')) {
    distinctWeeks[day.week()] = true
  }

  return Object.keys(distinctWeeks).length;
}

回答by user3507286

  function weeksInMonth(date = null){
    let firstDay = moment(date).startOf('month');
    let endDay = moment(date).endOf('month');

    let weeks = [];
    for (let i = firstDay.week(); i <= endDay.week(); i++){
      weeks.push(i)
    }

    return weeks;
  }