Trung Nguyen
Trung Nguyen

Reputation: 23

amCharts convert unixtime to readable date

I want to show stacked area chart using amCharts, anything else worked as well but date on it was parsed incorrectly.

"dataProvider": [{
    "date": 1482192000,
    "cars": 1587,
    "motorcycles": 650,
    "bicycles": 121
}

Property named as date on above data package cannot be converted to readable date like "DD/MM/YYYY"

Finally, the chart must show 30 days of chosen month.
Here is my CodePen:
CodePen Stacked Area Chart

Upvotes: 1

Views: 720

Answers (1)

xorspark
xorspark

Reputation: 16012

Your data and setup are both incorrect. Here's a list of what's wrong and how to fix them

1) dataDateFormat is used for parsing string dates, not formatting them. Since you're using unix timestamps, you don't need this property at all, so you can remove it.

2) Your unix timestamps must also be in milliseconds in order for this to work. Seconds will give you invalid times.

3) Your data must be sorted in ascending date order for it to render correctly. Your data is currently in mixed order.

As for your other questions:

To format your dates, you have to set the dateFormats array in your categoryAxis to the desired format strings as described here. For DD/MM/YYYY:

"categoryAxis": {
  // other properties omitted:
  "dateFormats": [{period:'fff',format:'JJ:NN:SS'},
    {period:'ss',format:'JJ:NN:SS'},
    {period:'mm',format:'JJ:NN'},
    {period:'hh',format:'JJ:NN'},
    {period:'DD',format:'DD/MM/YYYY'}, //you may need to change the entries for 'WW' and 'MM' as well, depending on the amount of visible data
    {period:'WW',format:'MMM DD'},
    {period:'MM',format:'MMM'},
    {period:'YYYY',format:'YYYY'}]
  // ...
}

To automatically zoom on chart load, you can add a rendered event similar to how the demos on the AmCharts website does it and call any of the zoom methods, for example:

"listeners": [{
  "event": "rendered",
  "method": function(e) {
    // different zoom methods can be used - zoomToIndexes, zoomToDates, zoomToCategoryValues
    e.chart.zoomToDates(new Date(2017, 1, 1), new Date(2017, 1, 15));
  }
}]

Here's an updated codepen with all of the aforementioned fixes here.

Upvotes: 1

Related Questions