Home > Software engineering >  D3 Trouble Altering Date
D3 Trouble Altering Date

Time:02-26

I'm importing a csv file and d3 treats every column as a string. The dates are currently stored like so: 2016-11-01. I'm trying to alter this column so that it will appear as Nov 16 (abbreviated month, abbreviated year).

Here is the code I have so far:

var dateParse = d3.timeParse("%Y-%m-%d") //matches the format in the csv
var monthParse = d3.timeParse("%m %y") //the format I'm looking for

var rowConverter = function (d) {
     return {
          date: dateParse(d.date)
          month: monthParse (d.date) //also tried monthParse(date)
     };
}

d3.dsv(",","my_csv.csv", rowConverter)

I expected this to give me two columns: one that would be the full date and one with the abbreviated month and year. I've confirmed the dateParse works correctly using console.log() statements. The monthParse, however, just results in NaNs. How can I get this column to populate correctly?

CodePudding user response:

d3.timeParse converts a string to a Date object. d3.timeFormat converts a Date object to a string.

You might be looking for something like this:

const dateParse = d3.timeParse("%Y-%m-%d");
const dateFormat = d3.timeFormat("%m %y");

function rowConverter(d) {
  const date = dateParse(d.date);
  return {
    date: date,
    month: dateFormat(date)
  };
}
  • Related