Hackerman
Hackerman

Reputation: 1378

How should I parse dateTime for Highcharts?

I'm pulling data from a csv where date(YYYYMMDD) and time (HHmm) are two of the columns. I already have a working parser that spits out array data points in [x, y] form. I just don't know how to parse my datetime (to use as the x-value) so Highcharts accepts it as a datetime. Just passing it in as one long number (YYYYMMDDHHmm) gives me a graph where all million points happen with a couple days in May...

Upvotes: 0

Views: 1022

Answers (1)

João Menighin
João Menighin

Reputation: 3225

You have two options depending on how is your data:

1) Set the correct data type as category

The documentation states:

The type of axis. Can be one of linear, logarithmic, datetime or category. In a datetime axis, the numbers are given in milliseconds, and tick marks are placed on appropriate values like full hours or days. In a category axis, the point names of the chart's series are used for categories, if not a categories array is defined.

To use it you would need your data in a millisecond format like:

[[1526688000000, 100], [1526774400000, 150], [1526860800000, 200]]

Fiddle: https://jsfiddle.net/y7kL4ccL/

Then to format your datetime, you can check here in the documentation.

2) Keeping the labels that way and provide a custom formatter

To do so you must set your xAxis.categories.type to category for Highcharts to use your point names as categories and then provide a custom xAxis.labels.formatter that transforms your string into whatever you want.

Example:

    xAxis: {
      type: 'category',
      labels: {
        formatter: function() {
          var year = this.value.substring(0, 4);
          var month = this.value.substring(4, 6);
          var day = this.value.substring(6, 8);
          return `${day}/${month}/${year}`;
        }
      }
    },

Fiddle: https://jsfiddle.net/qpad3qh7/

Upvotes: 1

Related Questions