JavaScript 添加天数而不增加月份

JavaScript add days not incrementing the month

我知道这个问题已经出现过很多次,我已经使用推荐的解决方案来创建我的函数,但我已经用它来滚动日历 next/prev 4 周。

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

来自控制台日志的示例:

第一次按'next':

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)

再按一次'next':

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 上 here

有什么想法吗?我在什么地方滑倒了吗?

您的函数可以大大简化,因为 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;
}

既然已经提供了修复此问题的方法,让我告诉您为什么您的方法不起作用。您首先创建 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;