Incorrect D3 date formatting date
I am getting some odd behavior from the socket functionality of D3.js, it seems that the key and rollup are converting test_date from Date object to string.
Here is my code:
var data = [{
"test_type": "x1",
"test_date": "2014-07-15"
}, {
"test_type": "x3",
"test_date": "2014-07-16"
}, {
"test_type": "x2",
"test_date": "2014-07-27"
}, {
"test_type": "x1",
"test_date": "2014-07-28"
}];
var parseDate = d3.time.format("%Y-%m-%d").parse;
data.forEach(function(d) {
d.test_date = parseDate(d.test_date);
});
var result = d3.nest()
.key(function(d) {
return d.test_type;
})
.key(function(d) {
return d.test_date;
})
.rollup(function(leaves) {
return leaves.length;
})
.entries(data);
And the result:
[{
"key": "x1",
"values": [{
"key": "Tue Jul 15 2014 00:00:00 GMT-0600 (Mountain Daylight Time)",
"values": 1
}, {
"key": "Mon Jul 28 2014 00:00:00 GMT-0600 (Mountain Daylight Time)",
"values": 1
}]
}, {
"key": "x3",
"values": [{
"key": "Wed Jul 16 2014 00:00:00 GMT-0600 (Mountain Daylight Time)",
"values": 1
}]
}, {
"key": "x2",
"values": [{
"key": "Sun Jul 27 2014 00:00:00 GMT-0600 (Mountain Daylight Time)",
"values": 1
}]
}]
I need the nested key value to be a date object, not a string. Does anyone know what might be causing this?
Here is a jsfiddle with the question http://jsfiddle.net/2ryahc9L/1/
source to share
A function (and an object) d3.time.format
works in two ways:
-
d3.time.format('%Y-%m-%d').parse('2014-08-29')
will return an objectDate
. It uses the format to know how to interpret the string given as an argument. -
d3.time.format('%Y-%m-%d')(new Date(2014, 7, 29))
will return a string formatted as2014-08-29'
.
Also, the keys in d3.nest
will always be string bound. You will need to combine both forms to achieve the desired behavior. Regards.
source to share
I found a solution that worked for me. I had a similar problem. I would like to insert timestamped data as a key. AmeliaBR wrote that keys are strings. But I would like to use the key as an object because it needs to be the x-axis of my chart.
var data = [{
"test_type": "x1",
"test_date": "2014-07-15"
}, {
"test_type": "x3",
"test_date": "2014-07-16"
}, {
"test_type": "x2",
"test_date": "2014-07-27"
}, {
"test_type": "x1",
"test_date": "2014-07-15"
}];
var parseDate = d3.time.format("%Y-%m-%d").parse;
I am using a different date field only for the nested data key without parsing the data as date / time.
data.forEach(function(d) {
d.key_date = d.test_date;
d.test_date = parseDate(d.test_date);
});
var result = d3.nest()
.key(function(d) {
return d.key_date;
})
.rollup(function(leaves) {
return leaves.length;
})
.entries(data);
In result
I add test_date
as an object again , since key_date
is a string.
result.forEach(function(d) {
d.test_date = parseDate(d.key);
});
I have no idea if this is a good way to do it. If not, please advice. Thank...
source to share