Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date format in D3.js

Tags:

d3.js

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); }); 

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

the csv file contains values:

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

what is the issue here?

like image 381
krishna_v Avatar asked Jul 18 '13 11:07

krishna_v


People also ask

What does d3 timeParse do?

The input string to d3. timeParse indicates what the date string should look like.


2 Answers

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.

like image 167
Adam Pearce Avatar answered Sep 30 '22 08:09

Adam Pearce


D3 version 4 has different time methods now.

https://keithpblog.org/post/upgrading-d3-from-v3-to-v4/ https://github.com/d3/d3/blob/master/CHANGES.md

Your source date

var d = {created_time : "2018-01-15T12:37:30+0000"} 

The structure of that date = %Y-%m-%dT%H:%M:%S%Z

I search google with "2018-01-15T12:37:30+0000" and it's suggestions provided the date structure string. Handy.

Create a timeParser to convert(parse) your date string into a date object

var parseDate = d3.utcParse("%Y-%m-%dT%H:%M:%S%Z") //parseDate(d.created_time) 

Now create a time formatter to return a formated date string for displaying.

var formatDate = d3.timeFormat("%b-%Y") return formatDate(parseDate(d.created_time)) 

i.e. Jan-1970

like image 27
Emile Avatar answered Sep 30 '22 09:09

Emile