我正在尝试调整Mike Bostock的泳道日历http://bl.ocks.org/bunkat/1962173,并用JSON文件替换随机数据生成函数。
d3.json("random.json", function(data) {
// console.log(d3.entries(data));
//var data = randomData()
var lanes = data.lanes;
var items = data.items;
var now = new Date();
.....
});
其中数据文件看起来像random()函数的输出:
{"lanes":[{"id":0,"label":"lane 0"},{"id":1,"label":"lane 1"},{"id":2,"label":"lane 2"},{"id":3,"label":"lane 3"},{"id":4,"label":"lane 4"}],"items":[{"id":0,"lane":0,"start":"2012-01-21T18:00:00.000Z","end":"2012-01-26T21:00:00.000Z","class":"past","desc":"This is a description."},{"id":1,"lane":0,"start":"2012-01-28T18:00:00.000Z","end":"2012-02-02T21:00:00.000Z","class":"past","desc":"This is a description."},{"id":2,"lane":0,"start":"2012-02-05T13:00:00.000Z","end":"2012-02-10T18:00:00.000Z","class":"past","desc":"This is a description."},{"id":3,"lane":0,"start":"2012-02-13T15:00:00.000Z","end":"2012-02-15T13:00:00.000Z","class":"past","desc":"This is a description."},{"id":4,"lane":0,"start":"2012-02-17T16:00:00.000Z","end":"2012-02-22T13:00:00.000Z","class":"past","desc":"This is a description."},{"id":5,"lane":0,"start":"2012-02-23T13:00:00.000Z","end":"2012-02-23T21:00:00.000Z","class":"past","desc":"This is a description."},{"id":6,"lane":0,"start":"2012-02-24T18:00:00.000Z","end":"2012-03-01T14:00:00.000Z","class":"past","desc":"This is a description."}
我得到的错误是:
TypeError:n.getFullYear不是函数
答案 0 :(得分:3)
解析完JSON之后,需要将日期从字符串显式转换为Date类型。
在给定的示例中,start和end变量创建为Date对象
var dtS = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate() + randomNumber(1,5), randomNumber(8, 16), 0, 0);
var dateOffset = randomNumber(0,7);
var dt = new Date(dtS.getFullYear(), dtS.getMonth(), dtS.getDate() + dateOffset, randomNumber(dateOffset === 0 ? dtS.getHours() + 2 : 8, 18), 0, 0);
您可以通过迭代项目并单独转换每个项目来实现此目的
items.forEach(function(d){
d.start = new Date(d.start);
d.end = new Date(d.end);
});
d3有一些帮助处理更复杂的日期字符串。您可以在此处详细了解它们:https://github.com/mbostock/d3/wiki/Time-Formatting#parse
var parseDate = d3.time.format.iso.parse;
items.forEach(function(d){
d.start = parseDate (d.start);
d.end = parseDate (d.end);
});
答案 1 :(得分:1)
我认为这是因为在您的data.items
中,start
和end
属性是字符串而不是日期(randomData()
函数将它们作为日期返回)。
...
var now = new Date();
items.forEach(function(d){
d.start = new Date(d.start);
d.end = new Date(d.end);
});
...