How to format datetime for (x,y) pair data for Hig

2020-06-27 07:24发布

问题:

My serialization method results a datetime string like this: "2014-07-09T12:30:41Z"

Why the following code does not work?

$(function () {
$('#container').highcharts({
    xAxis: {
        type: 'datetime'
    },

    series: [{
        data: [
            {x:"2014-07-09T12:30:41Z",y: 29.9},
            {x:"2014-09-09T12:30:41Z", y:71.5}
        ],
        name: "Teste"
    }]
});

});

this code work perfectly:

$(function () {
$('#container').highcharts({
    xAxis: {
        type: 'datetime'
    },

    series: [{
        data: [
            {x:Date.UTC(2014, 0, 1),y: 50},
            {x:Date.UTC(2014, 2, 1), y:20}
        ],
        name: "Teste2"
    }]
});

});

How to convert datetime format or configure highcharts to work with my data?

回答1:

Apparently Highcharts must be expecting the date as the number of milliseconds since "January 1, 1970, 00:00:00" universal time, that's what Date.UTC() retrieves, so you can accomplish the same thing doing this:

series: [{
    data: [
        {x:(new Date("2014-07-09T12:30:41Z")).getTime(),y: 29.9},
        {x:(new Date("2014-09-09T12:30:41Z")).getTime(), y:71.5}
    ],
    name: "Teste"
}]


回答2:

You can preprocess your data before using it in chart. Example - http://jsfiddle.net/Jx5n2/3851/

var data = [{
    x: "2014-07-09T12:30:41Z",
    y: 29.9
}, {
    x: "2014-09-09T12:30:41Z",
    y: 71.5
}],
len = data.length,
i = 0,
outData = [];

for (i = 0; i < len; i++) {
    outData[i] = {
        x: Date.parse(data[i].x),
        y: data[i].y
    }
}

$(function () {
    $('#container').highcharts({
        xAxis: {
            type: 'datetime'
        },
        series: [{
            data: outData
        }]

    });
});