Hbada
Hbada

Reputation: 31

Why is date from CSV file being outputted as NaN?

I've just finished a video on Lynda.com and can't get the same results the instructor gets using D3. I've created a simpler version of the files in question, and it still doesn't work. The console outputs NaN when I try to retrieve a date.

The CSV, as output from Excel, is:

Date,AM
1995-04-16,3.5
1995-04-17,14.0
1995-04-18,10.8

and the Javascript file contains:

d3.csv("bg_test_date_parsing.csv", function(d) {
  return {    Date: +d.Date,  AM: +d["AM"]  };
}, function(data) {
    console.log(data[1]);
});

The console in Mozilla gives me:

Object { Date: NaN, AM: 14 }

I can't proceed with any projects because I don't know where to start with importing dates properly. Videos on lynda.com just keep going, and I still don't get how to import and format dates. Also, the CSV originally was formatted 16-04-1995 as an example, outputted from a medical instrument, and I manually typed it into a year-month-day format that apparently D3 will work with. It took me many hours already using Google to get this far, so I'm obviously missing some key understanding.

Upvotes: 3

Views: 1335

Answers (1)

Joseph
Joseph

Reputation: 760

+d.Date isn't working the way you want. Calling + on 16-04-1995 is resulting in NaN. You can't convert that string to a number like that.

You can convert the string like this, var myDate = new Date('04-16-1995')

Unfortunately, your format is day-month-year, and javascript wants month-day-year.

See this question for what to do about that:

Convert dd-mm-yyyy string to date


Update As @GerardoFurtado notes in his comment, the d3 library has some built in date parsing options that can convert dates in different formats. See the links in his comment.

Using d3, you could convert the string to a Date like this:

var myDate = d3.timeParse("%d-%m-%Y")('16-04-1995')

or, within your loop:

Date: d3.timeParse("%d-%m-%Y")(d.Date)

Upvotes: 4

Related Questions