user3721240
user3721240

Reputation:

D3 Parse Date "2013-07-11T00:00:00" for line graph

How do I parse an array of dates like this: "2013-07-11T00:00:00", into something useable for a line graph? The graph will stretch back a full year.

I'm trying to create a dynamic graph like the one in the "Plotting a chart" section on this page.

It would be great if I could have the tick marks like that as well (Apr '13).

I'm currently using the following function in JavaScript:

var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%SZ").parse;

But it doesn't work.

Upvotes: 0

Views: 138

Answers (1)

Oleg
Oleg

Reputation: 9359

You have a trailing "Z" in your format specifier which makes your parser return null for the dates you give to it. Here's an example that works:

var parse = d3.time.format("%Y-%m-%dT%H:%M:%S").parse;
parse('2013-07-11T00:00:00'); // Thu Jul 11 2013 00:00:00 GMT+0200 (CEST)

You can use d3 time scales to display time-based axes with appropriate tick marks.

Edit:

I guess I misunderstood your question... here's another take which (hopefully) explains the usage of time scales and date formatting:

var scale = d3.time.scale(),
    axis = d3.svg.axis(),
    // Assuming you have your data as strings:
    data = ['2013-07-11T00:00:00', '2013-08-11T00:00:00', ...],
    range = [0, 500], // size of chart
    domain = d3.extent(data, function (d) { // generate the data extent (min,max)
        return new Date(d); // use Date instances for values
    });

// Configure the scale with domain and range:
scale.domain(domain).range(range);

// Use the above scale for the axis:    
axis.scale(scale)
    // Print the dates in "Mmm dd" format:
    .tickFormat(d3.time.format('%b %d'));

// Render the axis in your svg node:
svg.call(axis);

Upvotes: 1

Related Questions