如何在Javascript中获取月份中的周数?

时间:2015-08-27 19:47:11

标签: javascript calendar

我需要生成包含周数的年历,它应该如下图所示: enter image description here

然而,每个月获得一周的数字并不容易,因此它们不会重叠或丢失。我正在使用this SO question中的weekCount()函数。为了显示日历,我写了这段代码:

var year = parseInt($(this).text());
     var months = {1:'leden',2:'únor',3:'březen',4:'duben',5:'květen',6:'červen',7:'červenec',8:'srpen',9:'září',10:'říjen',11:'listopad',12:'prosinec'};
     var calendar = $('<div id="summary_search_form_menu"></div>');
     calendar.offset({top:$(this).offset().top + $(this).height() + 10}).css({right: '0px'});
     var cur_week = 0;
     for (var i=1;i<=12;i++) {
       var row = $('<div class="row"></div>');
       row.append('<div class="month button dark-blue">'+months[i]+'</div>');
       var week_count = weekCount(year, i);
       for (var week=1;week<week_count;week++) {
         cur_week++;
         row.append('<div class="week button blue">'+cur_week+'</div>');
       }
       calendar.append(row);
     }
     $('body').append(calendar);

如何正确显示周数?

1 个答案:

答案 0 :(得分:0)

好吧,我终于解决了这个问题。如果有人发现它有用,我会发布我的最终代码,它可以按照我的需要运行。

function weekCount(year, month_number) {
    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);
 }
 Date.prototype.getWeekNumber = function(){
    var d = new Date(+this);
    d.setHours(0,0,0);
    d.setDate(d.getDate()+4-(d.getDay()||7));
    return Math.ceil((((d-new Date(d.getFullYear(),0,1))/8.64e7)+1)/7);
  };

  var year = parseInt($(this).text());
  var months = {1:'leden',2:'únor',3:'březen',4:'duben',5:'květen',6:'červen',7:'červenec',8:'srpen',9:'září',10:'říjen',11:'listopad',12:'prosinec'};
  var calendar = $('<div id="summary_search_form_menu"></div>');
  calendar.offset({top:$(this).offset().top + $(this).height() + 10}).css({right: '15px'});
  var cur_week = 0;
  var col1 = $('<div id="summary_search_form_menu_col1"></div>');
  var col2 = $('<div id="summary_search_form_menu_col2"></div>');
  calendar.append(col1);
  calendar.append(col2);
  var col2_table = $('<div id="summary_search_form_menu_col2_table"></div>');
  col2.append(col2_table);
  for (var i=1;i<=12;i++) {
    var row = $('<div class="row"></div>');
    col1.append('<div class="month button dark-blue">'+months[i]+'</div>');
    var week_count = weekCount(year, i);
    var d = new Date(year, i-1, 1, 0,0,0);
    var first_week_in_month = d.getWeekNumber();
    for (var week=(cur_week == first_week_in_month ? 2 : 1);week<=week_count;week++) {
      cur_week++;
      row.append('<div class="week button blue">'+cur_week+'</div>');
    }
    col2_table.append(row);
  }
  $('body').append(calendar);