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)
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 :
Share Improve this question edited May 10, 2018 at 16:57 John Slegers 47.2k23 gold badges204 silver badges173 bronze badges asked Feb 24, 2016 at 12:30 ImoImo 1,4754 gold badges30 silver badges57 bronze badges 1TypeError: d.getMonth is not a function at d3_time_formats.b (d3.js:2517) at format (d3.js:2431)
-
which version of
d3
are you using, and on which browser does the error happen? – Mehdi Commented Feb 24, 2016 at 12:35
2 Answers
Reset to default 4You 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).
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744170265a4561502.html
评论列表(0条)