我对于日期数量不到1个月或3个月或6个月或特定时间段感到困惑。怎么做?。日期格式为MM / DD / YYYY。日期范围将动态添加。请任何人帮忙解决这个问题。
for ex
我的前阵列是
var array = ['01/05/2016','01/08/2016','01/09/2016','01/10/2016','01/11/2016','01/12/2016','12/25/2015','11/25/2015','11/29/2015','10/25/2015'];
var currentDate = '02/04/2016';
我必须循环数组并创建li元素。第一个li元素应该告诉数组的总数,而下一个li元素应该告诉最后一个月的日期数量,下一个li应该告诉最后3个月。如何隔离内部循环。
答案 0 :(得分:1)
你可以通过找出日期之间的差异来做这样的事情
var array = ['01/05/2016', '01/08/2016', '01/09/2016', '01/10/2016', '01/11/2016', '01/12/2016', '12/25/2015', '11/25/2015', '11/29/2015', '10/25/2015', '9/25/2015'];
var currentDate = '02/04/2016';
$('#range').change(function() {
var range = this.value;
//get the range value
var result = array.filter(function(v) {
// filter arry using filter()
var diff = Math.abs((new Date(currentDate)).getTime() - (new Date(v)).getTime());
// parse two dates and get difference between them
return Math.ceil(diff / (1000 * 3600 * 24)) <= range * 30;
// get the number of days difference and compare with the range
});
$('#list').html('Count : ' + result.length + '<br> Array : <pre> ' + JSON.stringify(result, null, 3) + '</pre>')
// showing result in json format
}).change()
// triggering change event
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="range">
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=6>6</option>
</select>
<div id="list"></div>
有用的问题:Get difference between 2 dates in javascript?
更新:根据您的需要,您可以执行类似此类操作
var array = ['01/05/2016', '01/08/2016', '01/09/2016', '01/10/2016', '01/11/2016', '01/12/2016', '12/25/2015', '11/25/2015', '11/29/2015', '10/25/2015'];
var currentDate = '02/04/2016';
$('#range').change(function() {
var range = this.value;
//get the range value
var result = range == 1 ? getRes(range).length : getRes(range).length - getRes($(':selected', this).prev().val()).length;
// getting count diff if range is greater than 1
$('#list').html('Count : ' + result);
// showing result in json format
}).change()
// triggering change event
function getRes(range) {
return array.filter(function(v) {
// filter arry using filter()
var diff = Math.abs((new Date(currentDate)).getTime() - (new Date(v)).getTime());
// parse two dates and get difference between them
return Math.ceil(diff / (1000 * 3600 * 24)) <= range * 30;
// get the number of days difference and compare with the range
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="range">
<option value=1>1</option>
<option value=3>3</option>
<option value=6>6</option>
</select>
<div id="list"></div>