我如何在underscore.js中查询日期?我知道我不能做一个“between”子句,但请看下面的代码作为例子。我的目标是根据用户指定的日期范围将JSON数据加载到图表中。
var testdata=[{"date": "1/8/2014", "y": 50, "z": 466, "a": 35},
{"date": "1/9/2014", "y": 325, "z": 201, "a": 85},
{"date": "1/10/2014", "y": 250, "z": null, "a": 40},
{"date": "1/11/2014", "y": 125, "z": 500, "a": 60},
{"date": "1/12/2014", "y": 50, "z": 466, "a": 35},
{"date": "1/13/2014", "y": 325, "z": 201, "a": 85}
];
daterange = _.select(testdata, function(getdates){ return getdates between '1/9/2014' and '1/12/2014';});
console.log(daterange);
更新:我在使用Gruff Bunny的例子中取代“startDate”和“endDate”时遇到一些麻烦。有什么建议?
var cb = function(start, end) {
$('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
alert("Callback has fired: [" + start.format('MMMM D, YYYY') + " to " + end.format('MMMM D, YYYY') + "]");
var testdata=[
{"date": "1/2/2014", "y": 250, "z": null, "a": 40},
{"date": "1/3/2014", "y": 125, "z": 500, "a": 60},
{"date": "1/4/2014", "y": 50, "z": 466, "a": 35},
{"date": "1/5/2014", "y": 325, "z": 201, "a": 85},
{"date": "1/6/2014", "y": 250, "z": null, "a": 40},
{"date": "1/7/2014", "y": 125, "z": 500, "a": 60},
{"date": "1/8/2014", "y": 50, "z": 466, "a": 35},
{"date": "1/9/2014", "y": 325, "z": 201, "a": 85},
{"date": "1/10/2014", "y": 250, "z": null, "a": 40},
{"date": "1/11/2014", "y": 125, "z": 500, "a": 60},
{"date": "1/12/2014", "y": 50, "z": 466, "a": 35}
];
_.each(testdata, function(data){
var dateParts = data.date.split('/')
data.date = new Date(dateParts[2], dateParts[0] - 1, dateParts[1])
});
var startDate = new Date(2014,0,9) ;
var endDate = new Date(2014,0,12) ;
var requiredData = _.filter(testdata, function(data){
return data.date >= startDate && data.date <= endDate;
});
答案 0 :(得分:6)
这些日期并不容易使用,因此请先将它们全部转换为javascript日期:
_.each(testdata, function(data){
var dateParts = data.date.split('/')
data.date = new Date(dateParts[2], dateParts[0] - 1, dateParts[1])
});
然后使用_.filter:
提取所需的数据var startDate = new Date(2014,0,9) ;
var endDate = new Date(2014,0,12) ;
var requiredData = _.filter(testdata, function(data){
return data.date >= startDate && data.date <= endDate;
});
答案 1 :(得分:1)
答案 2 :(得分:0)
您可能还想考虑使用像date.js这样的库来处理与日期相关的内容。
有点不相关,但仍然相关:我创建了一个关于按下基于日期的数据的截屏视频,使用下划线绑定到人力车图表,如果需要,请查看:http://tagtree.tv/d3-with-rickshaw-and-angular