Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding nvd3 x-axis date format

how is the date (x xAxis) formatted as "1025409600000"? I have been studying their documentation but can not figure how this works, it would make my life easier if someone would help me to understand how to change this to a 'normal' date format, like MMDDYYYY

This is the chart: http://nvd3.org/ghpages/stackedArea.html

Documentation: https://github.com/mbostock/d3/wiki/Time-Formatting

Thanks

like image 977
Sina H Avatar asked Oct 18 '13 21:10

Sina H


1 Answers

I've interpreted your question as how does 1025409600000 get formatted to MMDDYY as that's what's happening in the NV example.

In the example you pointed to the x axis has the dates almost in the format you want %m/%d/%Y (or MMDDYY) x axis date is formatted in the following line:

chart.xAxis
     .tickFormat(function(d) { return d3.time.format('%x')(new Date(d)) });

So the d3.time.format('%x') specifies the format of the date that is returned from (new Date(d)). The documentation you pointed at lets us know what the format will be and that is %x - date, as "%m/%d/%Y" which appears to be returning "%m/%d/%y". After reading the documentation I would have expected that the NV code would return the format you're after but you can easily get the format your after with:

d3.time.format('%m/%d/%Y')(new Date(d));

The new Date(d) takes the date data and converts it to a javascript date. The date data in the NV example is the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch) -see this MDN page. You can check this your self by typing new Date(1025409600000) at the console.

To get D3 to recognise your date format whether that be %m/%d/%Y or anything else you need to create a time format and then parse your date data. This is covered in the D3 Time Formatting page you provided a link to and I'll just adapt what's there to your example.

Create the time format you need in:

var format = d3.time.format("%m/%d/%Y");

And the use that to parse your data:

format.parse(d.Date);

Without your code I can't say exactly where this needs to go but it should be pretty clear. You can also try this out at the console.

Hope this helps

like image 99
user1614080 Avatar answered Oct 16 '22 03:10

user1614080