Search code examples
javascriptdated3.jsdate-formattime-format

I'm getting JavaScript error "d.getMonth is not a function" when trying to format a date using d3.time.format


I have a date value 2016-02-18 and I want to convert it to Feb 18.

I tried the following code, but it returns an error that get.month is not a function. I have also tried using format.parse(), but that didn't work either.

My code :

var dateLast = "2016-02-18";
var date = Date.parse(dateLast.replace(/-/g,"/"));
var format =  d3.time.format("%b-%d");
var dateConvert = format(date);
console.log(dateConvert);

The error message :

TypeError: d.getMonth is not a function at d3_time_formats.b (d3.js:2517) at format (d3.js:2431)


Solution

  • The D3.js way :

    Using d3.time.format, the most efficient way to achieve what you're going for, is this :

    var dateLast = "2016-02-18";
    var format = d3.time.format("%b %d");
    var dateConvert = format(new Date(dateLast));
    
    alert(dateConvert); // Output : Feb 18
    

    (See also this Fiddle)

    So, basically, you don't need this dateLast.replace or Date.parse at all. You can just use your date string directly as input of new Date().


    The vanilla JS way :

    Personally, I wouldn't even use d3 (or any other library) at all to format dates. You can do it in vanilla JS with about the same amount of code :

    var dateLast = "2016-02-18";
    var format = { month : 'short', day : 'numeric' };
    var dateConvert = new Date(dateLast).toLocaleDateString('en-US', format);
    
    alert(dateConvert); // Output : Feb 18

    (See also this Fiddle).