parseDate = d3.time.format("%Y") not working

d3.js

Solution

`parseDate`, the function "prepared" by d3, expects to be passed a string for parsing. Your years are (appropriately) numbers, so you would need to convert them to strings:

`parseDate(String(d.year));`

or

`parseDate(d.year.toString());`

However, keep in mind that the same result – a Date object – could be achieved natively, like this:

`var date = new Date(d.year, 0);// The required 0, is for January`

Problem

My chart is working completely as expected, except that my parseDate function doesn't want to give me correct dates on the x-axis. I'm sure this is something simple. Currently I'm adding d3.v2.min.js, without any additional helper libraries - do I need something else to get d3.time.format() working? Without parsing the date my data returns an x-axis with: ``` .960 .965 .970 .975 ``` rather than ``` 1960 1965 1970 1975 ``` The JSON is structured like this: ``` [{"year":1959,"average":315.97}, {"year":1960,"average":316.91}, {"year":1961,"average":317.64}, ...etc {"year":2011,"average":391.57}] ``` The code with the // commented sections being the issue: ``` <script> var margin = {top: 20, right: 20, bottom: 30, left: 50}, width = 920 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; ``` // parseDate below not working ``` var parseDate = d3.time.format("%Y").parse; var x = d3.time.scale() .range([0, width]); var y = d3.scale.linear() .range([height, 0]); var xAxis = d3.svg.axis() .scale(x) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .orient("left"); // data taking format d3.json("{{ asset('js/data_co2.json') }}", function(data) { ``` // parseDate() not working below Gives error: Uncaught TypeError: Object 1959 has no method 'substring' ``` data.forEach(function(d) { d.year = parseDate(d.year); d.average = +d.average; }); x.domain(d3.extent(data, function(d) { return d.year; })); y.domain([260, 420]); var area = d3.svg.area() .x(function(d) { return x(d.year); }) .y0(height) .y1(function(d) { return y(d.average); }); var svg = d3.select("#co2").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); svg.append("path") .datum(data) .attr("class", "area") .attr("d", area); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") .text("CO2 Levels (ppm)"); }); </script> ```

Original source