Moment.js how to get week of month? (google calendar style)

后端 未结 12 832
挽巷
挽巷 2020-12-03 13:56

I am using Moment.js and it is great. The problem I have now is that I can\'t figure out how to get the week of the month a certain date is. I can only find \"week of year\"

12条回答
  •  半阙折子戏
    2020-12-03 14:47

    When calculating the week of the month based on a given date, you have to take the offset into account. Not all months start on the first day of the week.

    If you want to take this offset into account, you can use something something like the following if you are using moment.

    function weekOfMonth (input = moment()) {
      const firstDayOfMonth = input.clone().startOf('month');
      const firstDayOfWeek = firstDayOfMonth.clone().startOf('week');
    
      const offset = firstDayOfMonth.diff(firstDayOfWeek, 'days');
    
      return Math.ceil((input.date() + offset) / 7);
    }
    

提交回复
热议问题