简体   繁体   中英

How do I filter dates in javascript to only get dates from the last 4 months?

How do I filter dates in javascript to only get dates from the last 4 months?

For example, if the last date I have is 2014-10-21, I only want data from July to October 2014 (so if I had 2013-10-14, it would be filtered out)

Here's what I have so far:

            $.each(dataArray, function(i, data){

        boundaryDates.push(data.values[0].x);
        boundaryDates.push(data.values.slice(-1).pop().x);
            });

            var maxDate=new Date(Math.max.apply(null,boundaryDates));
            var minDate=new Date(Math.min.apply(null,boundaryDates));

            //Convert Date
            var day = maxDate.getDay() < 9 ? '0'+maxDate.getDay():maxDate.getDay();
            var month = maxDate.getMonth() < 9 ? '0'+maxDate.getMonth():maxDate.getMonth();

            var mday = minDate.getDay() < 9 ? '0'+minDate.getDay():minDate.getDay();
            var mmonth = minDate.getMonth() < 9 ? '0'+minDate.getMonth():minDate.getMonth();

            var maximumDate = maxDate.getFullYear()+'-'+month+'-'+day;
            var minimumDate = minDate.getFullYear()+'-'+mmonth+'-'+mday;


    $.each(chartData, function(j, gid){
        if(gid.x >= minimumDate  && gid.x <= maximumDate ){
            gvalues.push(gid);
        }
    });

If I understand your question the right way, this would be the algorithm:

  • Take the last (maximum) date from the given array of dates
  • Copy that to a new date
  • Set the month of that copy to 4 months earlier ( setMonth )
  • Push that copy to a new array and
  • Push new dates (using setDate ) to that array, starting from the copied date until the date to push is the maximum date

In code:

 var date0 = new Date() ,dateBack = new Date(date0) ,last4MonthsDate = []; dateBack.setMonth(dateBack.getMonth()-4); last4MonthsDate.push(new Date(dateBack)); while (dateBack < date0) { dateBack.setDate(dateBack.getDate()+1); last4MonthsDate.push(new Date(dateBack)); } // show the result document.querySelector('#result').innerHTML = last4MonthsDate.map(function (v) { return [ v.getFullYear(), padLeft(v.getMonth()+1), padLeft(v.getDate()) ].join('-'); } ).join('<br>'); // helper for padding function padLeft(num, base, chr) { var len = (String(base || 10).length - String(num).length) + 1; return len > 0 ? new Array(len).join(chr || '0') + num : num; } 
 <div id="result"></div> 

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