通过 Javascript 获取每月的周数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2483719/
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-08-23 00:33:57  来源:igfitidea点击:

Get Weeks In Month Through Javascript

javascriptcalendar

提问by Stephen Watkins

In Javascript, how do I get the number of weeks in a month? I can't seem to find code for this anywhere.

在 Javascript 中,如何获得一个月中的周数?我似乎无法在任何地方找到此代码。

I need this to be able to know how many rows I need for a given month.

我需要这个才能知道给定月份我需要多少行。

To be more specific, I would like the number of weeks that have at least one day in the week (a week being defined as starting on Sunday and ending on Saturday).

更具体地说,我想要一周中至少有一天的周数(一周被定义为从周日开始到周六结束)。

So, for something like this, I would want to know it has 5 weeks:

所以,对于这样的事情,我想知道它有 5 周:

S  M  T  W  R  F  S

         1  2  3  4

5  6  7  8  9  10 11

12 13 14 15 16 17 18

19 20 21 22 23 24 25

26 27 28 29 30 31 

Thanks for all the help.

感谢所有的帮助。

回答by Ed Poor

Weeks start on Sunday

星期从星期日开始

This ought to work even when February doesn't start on Sunday.

即使二月不是在周日开始,这也应该有效。

function weekCount(year, month_number) {

    // month_number is in the range 1..12

    var firstOfMonth = new Date(year, month_number-1, 1);
    var lastOfMonth = new Date(year, month_number, 0);

    var used = firstOfMonth.getDay() + lastOfMonth.getDate();

    return Math.ceil( used / 7);
}

Weeks start on Monday

周从星期一开始

function weekCount(year, month_number) {

    // month_number is in the range 1..12

    var firstOfMonth = new Date(year, month_number-1, 1);
    var lastOfMonth = new Date(year, month_number, 0);

    var used = firstOfMonth.getDay() + 6 + lastOfMonth.getDate();

    return Math.ceil( used / 7);
}

Weeks start another day

周从另一天开始

function weekCount(year, month_number, startDayOfWeek) {
  // month_number is in the range 1..12

  // Get the first day of week week day (0: Sunday, 1: Monday, ...)
  var firstDayOfWeek = startDayOfWeek || 0;

  var firstOfMonth = new Date(year, month_number-1, 1);
  var lastOfMonth = new Date(year, month_number, 0);
  var numberOfDaysInMonth = lastOfMonth.getDate();
  var firstWeekDay = (firstOfMonth.getDay() - firstDayOfWeek + 7) % 7;

  var used = firstWeekDay + numberOfDaysInMonth;

  return Math.ceil( used / 7);
}

回答by santakllouse

None of the solutions proposed here don't works correctly, so I wrote my own variant and it works for any cases.

这里提出的所有解决方案都不能正常工作,因此我编写了自己的变体并且适用于任何情况。

Simple and working solution:

简单而有效的解决方案:

/**
 * Returns count of weeks for year and month
 *
 * @param {Number} year - full year (2016)
 * @param {Number} month_number - month_number is in the range 1..12
 * @returns {number}
 */
var weeksCount = function(year, month_number) {
    var firstOfMonth = new Date(year, month_number - 1, 1);
    var day = firstOfMonth.getDay() || 6;
    day = day === 1 ? 0 : day;
    if (day) { day-- }
    var diff = 7 - day;
    var lastOfMonth = new Date(year, month_number, 0);
    var lastDate = lastOfMonth.getDate();
    if (lastOfMonth.getDay() === 1) {
        diff--;
    }
    var result = Math.ceil((lastDate - diff) / 7);
    return result + 1;
};

you can try it here你可以在这里试试

回答by Joel

You'll have to calculate it.

你得计算一下。

You can do something like

你可以做类似的事情

var firstDay = new Date(2010, 0, 1).getDay(); // get the weekday january starts on
var numWeeks = 5 + (firstDay >= 5 ? 1 : 0); // if the months starts on friday, then it will end on sunday

Now we just need to genericize it.

现在我们只需要泛化它。

var dayThreshold = [ 5, 1, 5, 6, 5, 6, 5, 5, 6, 5, 6, 5 ];
function GetNumWeeks(month, year)
{
    var firstDay = new Date(year, month, 1).getDay();
    var baseWeeks = (month == 1 ? 4 : 5); // only February can fit in 4 weeks
    // TODO: account for leap years
    return baseWeeks + (firstDay >= dayThreshold[month] ? 1 : 0); // add an extra week if the month starts beyond the threshold day.
}

Note:When calling, remember that months are zero indexed in javascript (i.e. January == 0).

注意:调用时,请记住在 javascript 中月份索引为零(即一月 == 0)。

回答by Joseph Soares

The most easy to understand way is

最容易理解的方法是

<div id="demo"></div>

<script type="text/javascript">

 function numberOfDays(year, month)
 {
   var d = new Date(year, month, 0);
   return d.getDate();
 }


 function getMonthWeeks(year, month_number)
 {
   var $num_of_days       = numberOfDays(year, month_number)
    ,  $num_of_weeks      = 0
    ,  $start_day_of_week = 0; 

   for(i=1; i<=$num_of_days; i++)
   {
      var $day_of_week = new Date(year, month_number, i).getDay();
      if($day_of_week==$start_day_of_week)
      {
        $num_of_weeks++;
      }   
   }

    return $num_of_weeks;
 }

   var d = new Date()
      , m = d.getMonth()
      , y = d.getFullYear();

   document.getElementById('demo').innerHTML = getMonthWeeks(y, m);
</script>

回答by kennebec

function weeksinMonth(m, y){
 y= y || new Date().getFullYear();
 var d= new Date(y, m, 0);
 return Math.floor((d.getDate()- 1)/7)+ 1;     
}
alert(weeksinMonth(3))

// the month range for this method is 1 (january)-12(december)

// 此方法的月份范围是 1(一月)-12(十二月)

回答by siva

using moment js

使用时刻js

function getWeeksInMonth(year, month){

        var monthStart     = moment().year(year).month(month).date(1);
        var monthEnd       = moment().year(year).month(month).endOf('month');
        var numDaysInMonth = moment().year(year).month(month).endOf('month').date();

        //calculate weeks in given month
        var weeks      = Math.ceil((numDaysInMonth + monthStart.day()) / 7);
        var weekRange  = [];
        var weekStart = moment().year(year).month(month).date(1);
        var i=0;

        while(i<weeks){
            var weekEnd   = moment(weekStart);


            if(weekEnd.endOf('week').date() <= numDaysInMonth && weekEnd.month() == month) {
                weekEnd = weekEnd.endOf('week').format('LL');
            }else{
                weekEnd = moment(monthEnd);
                weekEnd = weekEnd.format('LL')
            }

            weekRange.push({
                'weekStart': weekStart.format('LL'),
                'weekEnd': weekEnd
            });


            weekStart = weekStart.weekday(7);
            i++;
        }

        return weekRange;
    } console.log(getWeeksInMonth(2016, 7))

回答by Webars

ES6 variant, using consistent zero-based months index. Tested for years from 2015 to 2025.

ES6 变体,使用一致的从零开始的月份索引。从 2015 年到 2025 年进行了多年的测试。

/**
 * Returns number of weeks
 *
 * @param {Number} year - full year (2018)
 * @param {Number} month - zero-based month index (0-11)
 * @param {Boolean} fromMonday - false if weeks start from Sunday, true - from Monday.
 * @returns {number}
 */
const weeksInMonth = (year, month, fromMonday = false) => {
    const first = new Date(year, month, 1);
    const last  = new Date(year, month + 1, 0);
    let dayOfWeek = first.getDay();
    if (fromMonday && dayOfWeek === 0) dayOfWeek = 7;
    let days = dayOfWeek + last.getDate();
    if (fromMonday) days -= 1;
    return Math.ceil(days / 7);
}

回答by imdadhusen

This is very simple two line code. and i have tested 100%.

这是非常简单的两行代码。我已经测试了 100%。

Date.prototype.getWeekOfMonth = function () {
    var firstDay = new Date(this.setDate(1)).getDay();
    var totalDays = new Date(this.getFullYear(), this.getMonth() + 1, 0).getDate();
    return Math.ceil((firstDay + totalDays) / 7);
}

How to use

如何使用

var totalWeeks = new Date().getWeekOfMonth();
console.log('Total Weeks in the Month are : + totalWeeks ); 

回答by August Lilleaas

You could use my time.js library. Here's the weeksInMonth function:

你可以使用我的 time.js 库。这是weeksInMonth 函数:

// http://github.com/augustl/time.js/blob/623e44e7a64fdaa3c908debdefaac1618a1ccde4/time.js#L67

weeksInMonth: function(){
  var millisecondsInThisMonth = this.clone().endOfMonth().epoch() - this.clone().firstDayInCalendarMonth().epoch();
  return Math.ceil(millisecondsInThisMonth / MILLISECONDS_IN_WEEK);
},

It might be a bit obscure since the meat of the functionality is in endOfMonth and firstDayInCalendarMonth, but you should at least be able to get some idea of how it works.

由于功能的主要内容是在 endOfMonth 和 firstDayInCalendarMonth 中,因此它可能有点晦涩,但您至少应该能够了解它是如何工作的。

回答by con

Thanks to Ed Poor for his solution, this is the same as Date prototype.

感谢 Ed Poor 的解决方案,这与 Date 原型相同。

Date.prototype.countWeeksOfMonth = function() {
  var year         = this.getFullYear();
  var month_number = this.getMonth();
  var firstOfMonth = new Date(year, month_number-1, 1);
  var lastOfMonth  = new Date(year, month_number, 0);
  var used         = firstOfMonth.getDay() + lastOfMonth.getDate();
  return Math.ceil( used / 7);
}

So you can use it like

所以你可以像这样使用它

var weeksInCurrentMonth = new Date().countWeeksOfMonth();
var weeksInDecember2012 = new Date(2012,12,1).countWeeksOfMonth(); // 6