[英]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
. 我有一个日期值2016-02-18
,我想将其转换为Feb 18
。
I tried the following code, but it returns an error that get.month
is not a function. 我尝试了以下代码,但它返回一个错误, get.month
不是一个函数。 I have also tried using format.parse()
, but that didn't work either. 我也尝试过使用format.parse()
,但这也不起作用。
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);
TypeError: d.getMonth is not a function at d3_time_formats.b (d3.js:2517) at format (d3.js:2431) TypeError:d.getMonth不是格式为d3_time_formats.b(d3.js:2517)的函数(d3.js:2431)
You need to pass Date
object into format
function (see documentation ): 您需要将Date
对象传递给format
函数(请参阅文档 ):
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)
Using d3.time.format
, the most efficient way to achieve what you're going for, is this : 使用d3.time.format
,实现目标的最有效方法是:
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. 所以,基本上,你根本不需要这个dateLast.replace
或Date.parse
。 You can just use your date string directly as input of new Date()
. 您可以直接使用日期字符串作为new Date()
输入。
Personally, I wouldn't even use d3 (or any other library) at all to format dates. 就个人而言,我根本不会使用d3(或任何其他库)来格式化日期。 You can do it in vanilla JS with about the same amount of code : 您可以使用大约相同数量的代码在vanilla JS中执行此操作:
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 ). (另见小提琴 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.