2

我有以下代码,需要计算两个日期之间的差异,但为什么我得到 diff is not a function?请注意,我使用的是 pikaday.js 和 moment.js,但为了简单起见,我对输入进行了硬编码。我在 StackOverflow 上看到过其他类似的帖子,但我是 moment.js 的新手,需要语法方面的帮助,而不仅仅是一个简短的句子作为答案。先感谢您。

<div>ARRIVAL</div>
<div>
  <input type="text" id="txtArrival" value="07/12/18">
</div>
<div>DEPARTURE</div>
<div>
  <input type="text" id="txtDeparture" value="15/12/18">
</div>
var aDate, dDate, a, b, days;

//get arrival and departure
aDate = new Pikaday({
  field: document.getElementById('txtArrival'),
  format: 'D MMM YYYY',
  onSelect: function() {
    console.log(aDate.getMoment().format('DD/MM/YY'));
  }
});

dDate = new Pikaday({
  field: document.getElementById('txtDeparture'),
  format: 'D MMM YYYY',
  onSelect: function() {
    console.log(dDate.getMoment().format('DD/MM/YY'));
  }
});

//calculate days
a = aDate.getMoment().format('DD/MM/YYYY');
d = dDate.getMoment().format('DD/MM/YYYY');
days = d.diff(a, 'days');
4

1 回答 1

2

format()返回string因此错误是预期的。您需要使用moment对象并对其.diff()执行

利用

days = dDate.getMoment().diff(aDate.getMoment(), 'days');

代替

days = d.diff(a, 'days');
于 2018-12-20T10:21:37.740 回答