简体   繁体   中英

How to format dates in Highcharts on x-axis?

I have dates stored in an array that needs to be display on the x-axis of the chart. How can I format the date so that it renders properly on x-axis?

{
  "xData": ["2020-10-01T19:30:00.000Z",
             "2020-10-02T19:30:00.000Z",
             "2020-10-03T19:30:00.000Z",
             "2020-10-04T19:30:00.000Z",
             "2020-10-05T19:30:00.000Z",
       ...
       ...
  ]
}

Highcharts.chart('container, {
  chart: {
    marginLeft: 40                  
  },
  title: {
    text: ''
  },
  xAxis: {
    categories: Date.UTC(xData),
  },
  yAxis: {
    title: {
      text: null
    }
  },
  series: [{
      data: dataset.data,
  }]
});

If you want to use x-axis with categories, map your date strings to an array with strings with the format you want.

    xAxis: {
        categories: dataset.xData.map(date => {
            return Highcharts.dateFormat('%Y-%m-%d', new Date(date).getTime());
        })
    }

Live demo: http://jsfiddle.net/BlackLabel/oL1ncjes/

API Reference: https://api.highcharts.com/class-reference/Highcharts#.dateFormat


But I think that a more suitable solution would be to create data in [x, y] format, use datetime x-axis type and labels format:

const processedData = dataset.data.map((dataEl, i) => {
    return [new Date(dataset.xData[i]).getTime(), dataEl] // x, y format
});

Highcharts.chart('container', {
    ...,
    xAxis: {
        type: 'datetime',
        labels: {
            format: '{value:%Y-%m-%d}'
        }
    },
    series: [{
        data: processedData
    }]
});

Live demo: http://jsfiddle.net/BlackLabel/y0dkzn1q/

API Reference: https://api.highcharts.com/highcharts/xAxis.type

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM