我有一个类似的数据数组:
var items = [
{ id: 84, "completedDate":"2019-01-26T17:45:07.895Z" },
{ id: 92, "completedDate":"2019-02-26T17:45:07.895Z" },
{ id: 123, "completedDate":"2019-03-26T17:45:07.895Z" },
{ id: 2353, "completedDate":"2019-04-26T17:45:07.895Z" }
];
我想返回一个只有少于30天的对象的数组。
我尝试过滤
var filtered = items.filter(function(item) {
return moment(item.completedDate) > moment.subtract(30, 'days');
});
这是我需要做的吗,还是有更好的方法呢?
答案 0 :(得分:1)
您不需要moment
来比较日期:
const compareDate = new Date();
compareDate.setDate(compareDate.getDate() - 30);
const filtered = items.filter(item => new Date(item.completedDate) > compareDate);
答案 1 :(得分:1)
这是一种类似的方法,不需要moment
。在这里,我们只获取当天的日期,将时间重置为当天的开始(您的用例可能需要也可能不需要),然后我们只使用普通的JS日期对象进行比较
var items = [
{ id: 84, "completedDate":"2019-01-26T17:45:07.895Z" },
{ id: 92, "completedDate":"2019-02-26T17:45:07.895Z" },
{ id: 123, "completedDate":"2019-03-26T17:45:07.895Z" },
{ id: 2353, "completedDate":"2019-04-26T17:45:07.895Z" }
];
var thirtyDaysAgo = new Date();
thirtyDaysAgo.setHours(0, 0, 0, 0);
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
var filtered = items.filter(function(item) {
var d = new Date(item.completedDate).getTime();
return d > thirtyDaysAgo;
});
console.log(filtered);
或者,一个更小的过滤器功能(如果不需要IE 11支持)将是:
var filtered = items.filter((item) => new Date(item.completedDate).getTime() > thirtyDaysAgo);
答案 2 :(得分:0)
尝试
items.filter( x=> x.completedDate > today.toISOString() );
var items = [
{ id: 84, "completedDate":"2019-01-26T17:45:07.895Z" },
{ id: 92, "completedDate":"2019-02-26T17:45:07.895Z" },
{ id: 123, "completedDate":"2019-03-26T17:45:07.895Z" },
{ id: 2353, "completedDate":"2019-04-26T17:45:07.895Z" }
];
var today = new Date("2019-04-20T17:45:07.895Z") // or: new Date()
today = new Date(+today - 30 *86400000)
let r= items.filter( x=> x.completedDate > today.toISOString() );
console.log(r);