moment JS get number of weeks in a month

how to get number of weeks in a month using javascript
moment js get first day of the week
moment-range
moment js get number of weeks between two dates
moment js get last day of month
how to get number of weeks in a year using moment js
moment get number of weeks in year
moment get current day in month

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.

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

Get week ranges for a given month? · Issue #529 · moment/moment , The next step is to find out a number of weeks in this month, we need to use moment range here. monthRange = moment.range(firstDay, endDay);  Below is working jsbin. Explanation of logic used. Getting the first and last day of the Month. firstDay = moment(startDate).startOf('month')endDay = moment(startDate).endOf('month') The next step is to find out a number of weeks in this month, we need to use moment range here. monthRange = moment.range(firstDay, endDay); weeks = []for (let mday of monthRange.by('days')) { if (weeks.indexOf(mday.week()) === -1) { weeks.push(mday.week()); }}

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

Find weeks of the month with Javascript Moment JS and Moment , 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  export const getNumWeeksInMonth = momentObj => { return moment. duration (moment (momentObj). endOf ('month') - moment (momentObj). startOf ('month')). weeks () + 1 } The above returns 4 when momentObj when momentObj is assigned the result of moment ('2015-02-01'), and 5 when moment ('2016-02-01') is used.

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!

moment JS get number of weeks in a month, <meta name="description" content="[weeks of month with Javascript, Moment and /libs/moment-range/4.0.1/moment-range.js"></script> <script> var indexOf = []. a")); // // Get the first and last day of the month firstDay = moment(startDate). isAfter(endDay)) { lastWeekDay = endDay; } //console.log("\n week number: " +​  JavaScript - get weeks in a month as array of start and end days - GetWeeksInMonth.js

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

weeks of month with Javascript and Moment and Moment Range , Get the number of days in the current month. moment("2012-02", "YYYY-MM").​daysInMonth() // 29 moment(  Can I use Moment.js to calculate the number of weeks between two dates? Specifically, I'm trying to work out the number of week between someone's birthday and the current date. I have the two dates as moments, but what next? //get todays date var today = moment () //get birth date var birthday = moment (year+"/"+month+"/"+day, 'YYYY-MM-DD');

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

Days in Month, moment().week(Number); moment().week(); // Number of year numbering differently, Moment.js added moment#week to get/set the localized week of the year. How to get difference between 2 Dates in Years, Months and days using moment.js Hot Network Questions awk print apostrophe/single quote

Week of Year, To get this wrapper object, simply call moment() with one of the supported input A calendar date part 2013-02 # A month date part 2013-W06-5 # A week date Note that the number of S characters provided is only relevant when parsing in  How would one use moment.js to get the number of days in the current month? Preferably without temporary variables.

Docs, Support the development of JSFiddle and get extra features ✌ return Math.ceil​(moment(day). //log week number based on first day of the week. 30. moment ().subtract ('seconds', 1); // Deprecated in 2.8.0 moment ().subtract (1, 'seconds'); As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.

Number of week of the year in Moment.js - JSFiddle, To get the date for beginning of week for a date in moment you can use The same technique can be used for start of month ( startOf('month') )  See the Pen JavaScript - Get the number of days in a month-date-ex- 3 by w3resource (@w3resource) on CodePen. Improve this sample solution and post your code through Disqus. Previous: Write a JavaScript function to get the current date. Next: Write a JavaScript function to get the month name from a particular date.

Comments
  • So are start and end ints or strings?
  • Possible repo of this and this??
  • What results are you getting and what were you expecting?
  • Note that you will need moment.js and moment-range.js to run this script.
  • This yeilds an incorrect result for December 2017. Results in 6 weeks, instead of 5
  • Same bug: Dec 2017 outputs 6 weeks instead of 5
  • @torvin I updated my answer with a corrected implementation. Would be awesome if you had the time to validate it as well at some point! In any case, thanks for the feedback on the old implementation! 👍
  • @jonruna Here is a take on the "old and incorrect implementation" (hopefully correct, though!): stackoverflow.com/a/60693500/352375
  • Old thread - I write this to go on record. If you run this with December 2017, the method returns 2. The reason this happens is because the first week (48) is greater than the last week (1), which is the first week of the next month. You try accounting for that with the "first > last" block, however, this ends up making the last week 49. Math should be: if( first > last ){ last = 52+last }
  • @eugene but if you do that you have to also edit the return : not add 1. am I correct?
  • your weeks start at sunday for you, but can we edit this to monday with your script?