JavaScript添加天数不会增加月份

时间:2015-07-28 21:04:19

标签: javascript getdate

我知道这个问题多次出现,我已经使用推荐的解决方案来创建我的功能,但我已经用它来滚动下一个/前4周的日历。

似乎发生的是第一次计算d + 28时它是正确的,但是当在函数中使用输出结果时它不起作用。

控制台日志中的示例:

第一次按“下一步”:

start Before = Tue Jul 28 2015 21:53:20 GMT+0100 (GMT Daylight Time)
start After = Tue Aug 25 2015 21:53:22 GMT+0100 (GMT Daylight Time)

第二次按“下一步”:

start Before = Tue Aug 25 2015 21:53:22 GMT+0100 (GMT Daylight Time)
start After = Sat Aug 22 2015 21:53:28 GMT+0100 (GMT Daylight Time)

所以它继续。

HTML:

 <!DOCTYPE html>
 <html ng-app="testApp">
 <head>
  <script src="https://code.angularjs.org/1.4.2/angular.js" data-require="angular.js@1.4.2" data-semver="1.4.2"></script>
  <link href="style.css" rel="stylesheet" />
  <script src="script.js"></script>
 </head>
 <body ng-controller="testController">
  <h1>Hello Plunker!</h1>
  <input type="button" ng-click="prevWeeks(start)" value="subtract 28 days" ng-model="start" />
  <input type="button" ng-click="nextWeeks(start)" value="add 28 days" ng-model="start" />
  <hr />
  <div>{{start}}</div>
 </body>
 </html>

JS:

var testApp = angular.module('testApp', []);

testApp.controller('testController', function($scope) {
  $scope.start = new Date();

  $scope.nextWeeks = function(d) {
    console.log('Next:');
    console.log('  start Before = ' + d);
    $scope.start = addDays(d, 28);
    console.log('    start After = ' + $scope.start);
    console.log('\n');
    }

  $scope.prevWeeks = function(d) {
    console.log('Previous');
    console.log('  start Before = ' + d);
    $scope.start = addDays(d, -28);
    console.log('    start After = ' + d);
    console.log('\n');
  }

});

function addDays(d, qty) {
  var dd = d.getDate();
  var mm = d.getMonth() + 1;
  var yyyy = d.getFullYear();
  if (dd < 10) dd = '0' + dd;
  if (mm < 10) mm = '0' + mm;
  var moreDate = new Date(yyyy, mm - 1, dd);

  var someDate = new Date();
  someDate.setDate(moreDate.getDate() + qty);

  return someDate;
}

在Plnkr上Law of Zero

有什么想法吗?我在某处溜了吗?

2 个答案:

答案 0 :(得分:1)

您的功能可以大大简化,因为Date类型会自动调整日期超出范围的月份。

function addDays(d, qty) {
    var dd = d.getDate();
    var mm = d.getMonth();
    var yyyy = d.getFullYear();
    return new Date(yyyy, mm, dd + qty);
}

另一种方式是:

function addDays(d, qty) {
    var newDate = new Date(d.getTime()); // Copy date
    newDate.setDate(d.getDate() + qty);
    return newDate;
}

答案 1 :(得分:1)

由于已经提供了解决方法,我告诉你为什么你的方式不起作用。您首先创建moreDate,将年和月调整为预期值,然后创建someDate,将其初始化为当前月份和当前年份。您将qty添加到日期并在someDate上设置该日期。然后计算是相对于今天而不是相对于作为参数提供的日期。例如,

var d = new Date(); //July 28 2015
d = addDays(d,28); //Aug 25 2015,works because we added 28 days to today
d = addDays(d,28); //Aug 22 2015!! Looks wrong, but is it?

最后一次电话明显看错了,但事实并非如此。单步执行代码:

  /*more code*/
  var moreDate = new Date(yyyy, mm - 1, dd); //Aug 25 2015

  var someDate = new Date(); //Catch!! July 28 2015
  someDate.setDate(moreDate.getDate() + qty); //Catch!!
  //the call above added 28+25 days to today which is Aug 22 2015
  return someDate;