'Undefined is not a function' 在 momentjs 函数中 DIFF

'Undefined is not a function' in momentjs function 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 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

可能出了什么问题?我真的不明白

问题是您正试图在字符串上调用 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