moment JS get number of weeks in a month

2019-07-23 12:46发布

问题:

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.

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.

回答1:

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.

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


回答2:


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;
}


回答3:

Can be easily done using raw 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



回答4:

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!



回答5:

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?



回答6:

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

Install moment with 'npm i moment'

Inside the ts file.

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)]