D3.js中的日期格式 [英] Date format in D3.js

查看:845
本文介绍了D3.js中的日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在csv中有一个列(日期),将日期存储在2003-02-01(y-m-d)中。我想将日期格式化为月份和年份,比如2003年4月。我该怎么做?

I have a column (date) in csv which stores the date in "2003-02-01"(y-m-d). I would like to format the date in month and year like Apr 2003. how do i do that?

var format = d3.time.format("%m-%Y");
data.forEach(function(d,i) {
d.date = format(d.date);
});

我得到以下错误错误: TypeError:n.getFullYear函数行:5

I am getting the following error Error: TypeError: n.getFullYear is not a function Line: 5

csv文件包含值:

200,300,400,288,123,2003-01-01
300,700,600,388,500,2003-02-01

这里的问题是什么?

推荐答案

Javascript不会自动将CSV文件中的值识别为日期,只是读它们作为字符串。 d3的时间函数可以非常容易地将它们转换为 datetime objects

Javascript doesn't automatically recognize the values in the CSV file as dates, just reading them in as strings. d3's time functions make it pretty easy to convert them to datetime objects:

> parseDate = d3.time.format("%Y-%m-%d").parse
> parseDate('2003-01-01')
Wed Jan 01 2003 00:00:00 GMT-0600 (Central Standard Time)

要按日期格式化日期,我们需要从日期对象到字符串:

To format the dates like you want, we need to go the other way, from a date object to a string:

> formatDate = d3.time.format("%b-%Y")
> formatDate(parseDate('2003-01-01'))
"Jan-2003"

我建议在程序中使用日期对象来表示日期,并且只在需要显示日期对象时将其格式化为字符串。

I would recommend representing your dates within your program with date objects and only formatting them as strings when you need to display them.

这篇关于D3.js中的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆