0

I'm trying to use d3.timeFormat() to convert a date formatted like this: 2017-09-19T00:00:00 to a more readable: Sep 19, 2017. I've tried numerous variations on the following code with no luck:

.append('td')
   .text(function (d, i) { 
        if (i === 0) {
           var parseDate = d3.timeFormat("%m %d, %Y");
           return parseDate(d.value)
         }
         else {
            return d.value; 
         }

     });

Here is what it's returning: 0NaN NaN NaN.

I'm guessing that the value I have is a string, and I need to convert it to a date/time object that can then be rendered/formatted as desired, but I can't figure out how to make it work? Then again, I could be wrong, as I'm a UX guy and not a programmer by trade.

Any help explaining how I should approach this is greatly appreciated. Thanks.

Herb Himes
  • 41
  • 5

1 Answers1

1

Yes, you need to convert the string to a date. Also I think you want %b for the abbreviated month:

var aDate = new Date(d.value)
var parseDate = d3.timeFormat("%b %d, %Y");
console.log("Date: ", parseDate(aDate))

// Prints:
// Date: "Sept 18, 2017"
Mark
  • 90,562
  • 7
  • 108
  • 148
  • Worked like a charm! Thanks. So the first line in your code sample is what converts the string to a date object, and the second parses it and formats it, correct? Just want to make sure I understand the syntax for future use :). – Herb Himes Oct 04 '17 at 20:04
  • First line creates a date object from the string. The second line creates a formatting function that is called in the third line with `parseDate(aDate)`. – Mark Oct 04 '17 at 20:12
  • There is no need to convert to a Date, the OP could just reformat the string without producing a Date object. Use of the built-in parser is [*not recommended*](https://stackoverflow.com/a/2587398/257182). – RobG Oct 04 '17 at 23:00