Javascript 在后台记录绝对时间,在前端显示相关时间

Javascript 在后台记录绝对时间,在前端显示相关时间,javascript,momentjs,Javascript,Momentjs,我有一个帖子的数据库。对于每个帖子,我想保存不同用户上次打开的时间。因此,我决定在后端保存绝对时间(即,通过moment()),并在前端显示相关时间(即,通过fromNow(),例如,2天前) 在后端: var PostSchema = new mongoose.Schema({ ... ... lastOpens: { type: Array, default: [] }, }); PostSchema.methods.updateLastOpens = function (user

我有一个
帖子的数据库
。对于每个
帖子
,我想保存不同用户上次打开的时间。因此,我决定在后端保存绝对时间(即,通过
moment()
),并在前端显示相关时间(即,通过
fromNow()
,例如,
2天前

在后端:

var PostSchema = new mongoose.Schema({
  ... ...
  lastOpens: { type: Array, default: [] },
});

PostSchema.methods.updateLastOpens = function (userId, cb) {
  ... ...
  this.lastOpens.push({ time: moment(), userId: userId });
};
在前端:

alert(JSON.stringify(post.lastOpens[j].time))
var x = post.lastOpens[0].time.fromNow()
但是,前端的第一行显示了一个很长的对象
{“\u isValid”:true,“\u d”:“2017-04-20T02:42:50.932Z”,“\u locale”:{“\u dayOfMonthOrdinalParseLenent”:{},
,第二行显示
类型错误:post.lastOpens[0]。time.fromNow不是一个函数


有人知道哪里出错以及如何实现这一点吗?

您从后端获取的数据可能不是
时刻对象
。因此,您无法在此基础上调用
fromNow
函数。要从现在起调用,您可以通过在
时刻构造函数中传递
\u d
将数据转换为时刻对象,然后然后像这样对该对象调用
fromNow

var x = moment(post.lastOpens[j].time._d).fromNow()

您正在将一个moment.js对象推送到数组中,然后将其字符串化,因此您看到的是字符串化的moment对象,而不是日期。您可能应该推
{time:moment().fomat('YYYY-MM-DD'),…}
或类似的对象。我在
alert()
中对其进行了字符串化,但在
var x=post.lastOpens[0].time.fromNow()中没有
。是的,但您应该考虑的是,后端将序列化对象,即您看到的长Json,并将其发送到前端。当它到达前端时,它不再是矩对象。它是一个普通的Json对象,具有数据但没有方法。我将重新创建矩()从前端的.time的内容中删除,然后重试该代码。