0

我想用 HTML 打印星期、年份,即43,2013. 此外,当我按下prev按钮时,它应该打印42,2013,然后按下下一步我应该得到44,2013.

我可以做一个月,一年,即October,2013下个月,但不能做一周。

这是我一个月的代码。请帮助我编写一周的代码。

function monthNav(nav) {

  if(nav == 'prev') {

    var newMonth = cur_dat.getMonth() - 1;
    var newYear = cur_dat.getFullYear();
    if(newMonth < 0) {
      newMonth = 11;
      newYear -= 1;
    }

    cur_dat.setMonth(newMonth);
    cur_dat.setFullYear(newYear);
    curMonthYear = month[newMonth] + ", " + newYear;
    $("#mNav").html(curMonthYear);


  } else {

    var newMonth = cur_dat.getMonth() + 1;
    var newYear = cur_dat.getFullYear();
    if(newMonth > 11) {
      newMonth = 0;
      newYear += 1;
    }

    if(newYear == curYear && newMonth > curMonth) {
      return false;
    }
    cur_dat.setMonth(newMonth);
    cur_dat.setFullYear(newYear);
    curMonthYear = month[newMonth] + ", " + newYear;
    document.getElementById('periodVal').value=curMonthYear;
    $("#mNav").html(curMonthYear);

  }

}
4

3 回答 3

1

尝试这个 -

function getWeeks(d) {
 var first = new Date(d.getFullYear(),0,1); //start of the year
 var dayms = 1000 * 60 * 60 * 24;
 var numday = ((d - first)/dayms)
 var weeks = Math.ceil((numday + first.getDay()+1) / 7) ; 
 return weeks
}
alert(getWeeks(new Date("1 Dec 2012"))); //end of the year     

并在此处检查您的代码http://jsbin.com/ugesex/29/edit

于 2013-10-28T06:06:18.137 回答
0

rubyist 的函数可以很好地获取日期,只需将 Math.ceil 更改为 Math.floor 就可以了。我冒昧地清理了您的原始代码。

function weekNav(nav) {

//just create a +1 or -1 valued variable here so you dont
//have to write the same code over agian.
  if (nav == 'prev') {
    var state = -1;
  } else {
    var state = 1;
  }

  var d = new Date();
  var newWeek = cur_dat.getWeek(d) + state;
  var newYear = cur_dat.getFullYear() + state;

  if (newWeek < 0) {
    newWeek = 52;
    newYear -= 1;
  } else if (newWeek > 52) {
    newWeek = 0;
    newYear += 1;
  }
  //display to HTML like monthNav()
}
/* Editted this function to adjust for last few days of the year */
function getWeeks(d) {
  var first = new Date(d.getFullYear(),0,1);
  var dayms = 1000 * 60 * 60 * 24;
  var numday = ((d - first)/dayms);
  var getDay = (numday + first.getDay()+1 )/ 7;
  var weeks = Math.round(getDay);     
  if ((numday+first.getDay()+1/7) > 365) {
    weeks++;
  }
  return weeks;
}
于 2013-10-28T07:01:53.560 回答
0

我可以使用以下方法获得所需的结果。关键是将天数和除法作为两个 sep 函数相加 - 否则我会得到疯狂的结果。

    var weeksCount = function (year, month_number) {
        var firstOfMonth = new Date(year, month_number, 1);
        var day = firstOfMonth.getDay();
        var lastOfMonth = new Date(year, month_number + 1, 0);
        var lastDate = lastOfMonth.getDate();
        var result = day + lastDate;
        result = Math.ceil(result / 7);
        return result;
    };
于 2018-05-14T15:07:50.653 回答