如何在javascript中过滤日期以仅获取过去4个月的日期?
例如,如果我的最后一个日期是2014-10-21,我只想要2014年7月到10月的数据(所以如果我有2013-10-14,它会被过滤掉)
这是我到目前为止所拥有的:
$.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);
}
});
答案 0 :(得分:1)
如果我以正确的方式理解你的问题,那就是算法:
setMonth
)setDate
)推送到该数组,从复制日期开始直到推送日期为最长日期在代码中:
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>