简体   繁体   中英

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)

You need to pass Date object into format function (see documentation ):

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

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM