首页 > 解决方案 > 时刻js添加功能不起作用

问题描述

从字面上看, moment().add() 在我的 js 代码中不起作用。

var theDate = moment(event.start.format("YYYY-MM-DD HH:mm")); //start Date of event 
var checkquarter = theDate.add(30, 'minutes');
var plus = 30;
if (userDuration == '45') {
  plus = 45;
}
for (var i = 0; i < excludedList.length; i++) {

  var excludedTomorrow = moment(excludedList[i]["excludedDate"]).format("YYYY-MM-DD HH:mm"); //start Date of event that should be excluded

  var endtime = moment(excludedTomorrow).add(plus, 'minutes'); //endTime of event that should be excluded
  if (excludedList[i]["id"] == 'aaa@gmail.com') {
    console.log(endtime);
    console.log(plus);
    console.log(theDate);
    console.log(checkquarter);

  }
  //var endtimeForCompare = moment(endtime);
  if (theDate >= excludedTomorrow && theDate < endtime && Id == excludedList[i]["id"]) {

    return false;
  }
}
<script src='https://momentjs.com/downloads/moment.js'></script>

在这段代码中,我使用了两次moment add。首先是检查季度,它在 Date 变量中增加了 30 分钟。第二个是结束时间,它是从我的数据库中获得的 excludeTomorrow 加上分钟。

如果您看到此图像,这是控制台 控制台响应 ,它按顺序显示结束时间、加号、日期和检查季度变量。但是,如您所见,它们没有添加任何内容。

我的 momentJS 脚本是,

<script src='https://momentjs.com/downloads/moment.js'></script>

标签: javascriptfullcalendarmomentjs

解决方案


您应该克隆theDatecheckQuarter,因为 Moments 是可变的。

https://momentjs.com/docs/#/manipulating/

这意味着它var checkquarter = theDate.add(30, 'minutes');正在发生变化theDate,并且checkQuarter只是对theDate.

运行以下命令时查看控制台:

var theDate = moment("1995-12-25 14:00");
console.log(theDate.toString());
var newDate = theDate.add(10, "minutes");
console.log(theDate.toString());
console.log(newDate.toString());
var anotherDate = moment(theDate);
anotherDate.add(10, "minutes");
console.log(anotherDate.toString());
console.log(theDate.toString());

推荐阅读