【问题标题】:moment js add function is not working时刻js添加功能不起作用
【发布时间】:2018-07-17 10:43:09
【问题描述】:

从字面上看,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;
  }
}
&lt;script src='https://momentjs.com/downloads/moment.js'&gt;&lt;/script&gt;

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

这是控制台 console response 如果您看到此图像,它会按顺序显示结束时间、加号、theDate、checkquarter 变量。但是,如您所见,它们没有添加任何内容。

momentJS 我的脚本是,

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

【问题讨论】:

  • 不要被控制台上的显示方式所欺骗。您是否真的尝试从对象中获取更新的日期时间? :) 见this image。如果您真的想查看更新后的值,请观察控制台上打印的 moment 对象的 _d 属性。

标签: javascript fullcalendar momentjs


【解决方案1】:

您应该将 theDate 克隆到 checkQuarter,因为 Moments 是可变的。

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

这意味着var checkquarter = theDate.add(30, 'minutes'); 正在改变theDatecheckQuarter 只是对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());

【讨论】:

  • 谢谢!!起初,if 中的条件不正常,所以函数不会返回 false。起初,我认为 add 函数有问题,但知道我解决了 var checkquarter = theDate.add(30, 'minutes'); 之间的区别的问题和 var checkquarter = moment(theDate).add(30, 'minutes');第一个实际上改变了日期值..!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-19
  • 2012-02-08
  • 1970-01-01
相关资源
最近更新 更多