说,我有一个JSON数据
[
{
"transaction": "34",
"date": "Mar 12 2016 10:00:00 AM"
}, {
"transaction": "21",
"date": "Mar 12 2016 10:00:00 AM"
}, {
"transaction": "40",
"date": "Mar 13 2016 10:00:00 AM"
}, {
"transaction": "40",
"date": "Mar 14 2016 10:00:00 AM"
}
]
一天内可能会有多笔交易。如何从此JSON数据中获取最近一周或一个月的交易记录?
答案 0 :(得分:0)
结帐
数据似乎无效,我将其从Object更改为
我添加了上个月数据的代码,上一周
var data = [{
"transaction": "34",
"date": "Apr 12 2017 10:00:00 AM"
}, {
"transaction": "21",
"date": "Apr 12 2017 10:00:00 AM"
}, {
"transaction": "40",
"date": "Mar 15 2016 10:00:00 AM"
}, {
"transaction": "50",
"date": "Jan 13 2017 10:00:00 AM"
}, {
"transaction": "40",
"date": "Mar 13 2017 10:00:00 AM"
}, {
"transaction": "40",
"date": "Mar 14 2016 10:00:00 AM"
}];
//It will return dates diff in no. if months
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
//It will gets the last month date
function getLastMonth(){
var x = new Date();
x.setDate(1);
x.setMonth(x.getMonth()-1);
return x;
}
var prevMonthDate = getLastMonth();
var lastMonthData = data.filter(function(v){
return monthDiff(new Date(v.date),prevMonthDate) < 1;
});
//This is the data for last one Month
console.log(lastMonthData);
//It will return dates diff in no. if Weeks
function weekDiff(d1,d2){
var dif = Math.round(d1-d2);
return Math.ceil(dif/1000/60/60/24/7);
}
//It will gets the last week date
function getLastWeek(){
var today = new Date();
var lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
return lastWeek ;
}
var prevWeekDate = getLastWeek();
var lastWeekData = data.filter(function(v){
return weekDiff(new Date(v.date),prevWeekDate) == 1;
});
//This is the data for last one Week
console.log(lastWeekData);
<强> Working example in Fiddle 强>