简体   繁体   中英

How can I get data of last week or last month in JSON data?

Say, I have a JSON data

[
    {
        "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"
    }

]

There may be several transactions in one day. How can I get the most recent one week's or month's transaction records from this JSON data?

Checkout below

Data seems not valid, i changed it from Object to Array

I added code for Last one month Data,Last One week

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM