我有以下代码:
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
可能有什么问题?我真的不理解
答案 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