'未定义不是一个功能'在momentjs函数DIFF

时间:2015-04-12 17:02:04

标签: node.js momentjs

我有以下代码:

var dateFormat = 'YYYY-MM-DD HH:mm:ss';

var time_margin = 10;

var last_message = moment().format(dateFormat);

var comparison = moment(last_message).add(time_margin, 'seconds').format(dateFormat);
var actualtime = moment().format(dateFormat);
var secondsDiff = actualtime.diff(comparison, 'seconds');
console.log("secondsdiff",secondsDiff);

它与var secondsDiff = actualtime.diff(comparison, 'seconds');

一起在Missing error handler on "socket". TypeError: undefined is not a function.中崩溃

comparison 2015-04-12 18:00:41 actualtime 2015-04-12 18:00:42

可能有什么问题?我真的不理解

1 个答案:

答案 0 :(得分:2)

问题在于您尝试在字符串上调用diff。当您致电moment().format(dateFormat)时,结果是字符串,而不是moment的实例。

要解决此问题,您需要调出diff而不进行格式化:

var dateFormat = 'YYYY-MM-DD HH:mm:ss';
var time_margin = 10;
var last_message = moment().format(dateFormat);

var comparison = moment(last_message).add(time_margin, 'seconds').format(dateFormat);
var secondsDiff = moment().diff(comparison, 'seconds');
console.log("secondsdiff",secondsDiff);
// => secondsdiff -9