Highcharts X-Axis time from JS date

2019-04-11 00:59发布

问题:

I want to visualize the temperature from my database with Highcharts. The JS data array looks like the following:

[date object, value]

For example:

[Fri Mar 04 2016 01:39:10 GMT+0100 (Central Europe Standard Time), 20.5]

As you can see, I have a date object and a value. So my problem is to format the x-axis that it shows my dates, in best case formatted to HH:MM. It seems like I have use the xAxis type datetime, but this doesn't work.

xAxis: {
    type: 'datetime'
    // ...
}

Do you know a solution for this problem?

回答1:

Highcharts takes in datetime in the form of timestamps in milliseconds. You are providing a Date object. Instead of just inserting the Date object use the getTime() function of the Date object to get the timestamp.

For example (JSFiddle):

$(function () {
    // The timestamp of the current time
    var timestampNow = new Date().getTime();
    // The timestamp one hour from now
    var timestampOneHour = new Date(timestampNow + (3600 * 1000)).getTime();

    $('#container').highcharts({
        xAxis: {
            type: 'datetime'
        },
        series: [{
            data: [
                [timestampNow, 1],
                [timestampOneHour, 2]
            ]
        }]
    });
});