所以我想比较post对象中的两个日期。我试图比较date对象,但是返回了NaN。然后,我尝试通过在这些日期上使用.now()将其转换为自1970年以来的毫秒,但它返回了以下错误:
It happens: TypeError: a.date.now is not a function我尝试了typeof a.date,这个返回了string。我不知道为什么不能使用.now()方法。有人能帮我吗?
角服务的整体功能
getPosts(section) {
return this.http.get(url + '/forum/getPosts/' + section )
.map( (posts: any) => {
// posts should be ordened based on latest replies. If there are no replies yet, we compare it to the date
// of the original post
posts.obj.sort((a, b) => {
const aHasReplies = a.replies.length !== 0;
const bHasReplies = b.replies.length !== 0;
if (aHasReplies && bHasReplies ) {
return a.replies.slice(-1, 1)[0].date - b.replies.slice(-1, 1)[0].date;
} else if ( aHasReplies && !bHasReplies) {
return a.replies.slice(-1, 1)[0].date - b.date;
} else if ( !aHasReplies && bHasReplies) {
return a.date - b.replies.slice(-1, 1)[0].date;
} else {
console.log(a.date.now());
return a.date - b.date;
}
});
return posts;
});
}发布于 2018-10-02 14:06:28
如果这是您的意思,那么它应该是对象,而不是字符串,因为没有“日期字符串”。除此之外,还应尝试:
new Date(a.date).getTime()因为.now是一个静态方法,所以您总是使用它作为Date.now()
这意味着,Date.now()总是返回自UNIX时代以来经过的毫秒。要转换为unix,请使用getTime。
如果要比较它们,请在没有转换的情况下比较两个日期。
但是请记住,unix时间以秒为单位,javascript方法以毫秒为单位返回。如果您需要精确的unix时间,除以1000。
发布于 2018-10-02 14:06:17
您可以使用常规的javascript比较器(如< and >等)比较年月日格式(Yyyy Dd)中的两个日期。
发布于 2018-10-02 14:09:12
我建议使用moment.js库(https://momentjs.com/docs/)解析字符串中的日期。这样你就能得到一些东西
let date = moment(a.date)
https://stackoverflow.com/questions/52610003
复制相似问题