本周[Javascript]

时间:2015-12-01 08:36:04

标签: javascript angularjs

我使用此功能获取当前周

 Date.prototype.getWeek = function(start)
{
  start = start || 1;
  today = new Date(this.setHours(0, 0, 0, 0));

  var day = today.getDay() - start;
  date = today.getDate() - day;

  var giorni = [];
  var currdate;
  for(var i = 0;i<7;i++){  
    if(getNumberOfDays(today.getFullYear(),today.getMonth()) == currdate){
      var changed=1;
      var newdate=new Date(today.getFullYear(),today.getMonth()+1,1);
      giorni.push(newdate);      
    }else{
      if(changed==1){
        var dt = newdate.getDate();
        giorni.push(new Date(today.getFullYear(),today.getMonth()+1,dt+1));
        newdate = new Date(today.getFullYear(),today.getMonth(),dt+1);

      }else{

        giorni.push(new Date(today.setDate(date+i)));
      }
    }

    currdate = date+i;

   }
}
var Dates = new Date().getWeek();

但在本周它显示错误的日期..(11月30日至11月6日)enter image description here

有什么建议吗? (这是plunker - &gt; plnkr.co/edit/48NyxngWNGIlOps1Arew?p=preview)

2 个答案:

答案 0 :(得分:1)

以下是使用momentjs开始本周和其他事情的答案。

    function getWeekFor(dateTime) {
        var days = [];
        var sunday = moment(dateTime).startOf('week');

        for (var i = 1; i < 8; i++) {
            days.push(moment(sunday).add(i, 'days'));
        }

        return days; // returns a list of moment objects
    }

    function shiftWeek(add, dateTime) {
      // this will just increment or decrement the week
      var sunday = moment(dateTime).startOf('week');
      sunday.add(1, 'd');

      if (add) {
        sunday.add(1, 'w'); 
      } else {
        sunday.subtract(1, 'w'); 
      }

      return sunday; // returns a moment object
    }

    function getWeekDate(dateTime) {
        var sunday  = moment(dateTime).startOf('week');

        var monday = sunday.add({day: 1}).clone();

        return 'Week Commencing ' + monday.format('Do'); // a nicely formatted string of the week commencing
    }

    function getStartOfWeek(dateTime) {
        var sunday  = moment(dateTime).startOf('week');

        var monday = sunday.add({day: 1}).clone();

        return monday; // the monday that started the week as a moment object
    }

这是非常简单和自我解释的。它使用传递startOf的方法addw作为要添加的单位。 w == week

如果你不想要一个时刻对象,那么你可以从中得到一个其他对象列表:

moment().toDate(); // returns javascript Date
moment().toArray(); // This returns an array that mirrors the parameters from new Date()
moment().toJSON(); // it will be represented as an ISO8601 string, adjusted to UTC.

答案 1 :(得分:0)

这是因为您手动更改日期

giorni.push(new Date(today.getFullYear(),today.getMonth()+1,dt+1));

而不是尝试

var today = new Date()
today.setDate(today.getDate()+1);
giorni.push(new Date(today.getTime()));