Question

i´m using the highchart plungin for my new project i have just notice that in my data array, the date must have one month less because in javascript the month´s starts in 00 (not in 01). My array with the values are something like this (:

var usdeur = [
    [Date.UTC(2004, 3, 31), 0],
    [Date.UTC(2004, 4, 1), 0.134879956838416],
    [Date.UTC(2004, 4, 2), 0.471580293538753],
    [Date.UTC(2004, 4, 3), 0.473578515121543],
    [Date.UTC(2004, 4, 4), 0.474577625912938],
];

Any idea of how can i subtract one month for each date to make the chart work fine?

Thank you and sorry for my terrible english.

Était-ce utile?

La solution

If you can change how it's generated, generate this instead

var usdeur = [
    [Date.UTC(2004, 3 - 1, 31), 0],
    [Date.UTC(2004, 4 - 1, 1), 0.134879956838416],
    [Date.UTC(2004, 4 - 1, 2), 0.471580293538753],
    [Date.UTC(2004, 4 - 1, 3), 0.473578515121543],
    [Date.UTC(2004, 4 - 1, 4), 0.474577625912938],
];

If you have no way of fixing the generated code, you may be able to put a custom Date.UTC function in before it's evaluated, and undo this after.

(function () {
    var utc = Date.UTC, slice = Array.prototype.slice;
    Date.UTC = function () { // method to take `1` based months
        var args = slice.apply(arguments);
        if (args.length > 2) // fix your months
            args[1] -= 1;
        return utc.apply(Date, args);
    };
    Date.UTC.restore = function () { // method to undo changes
        Date.UTC = utc;
    };
}());
// eval your array
// ...
// restore original behaviour
Date.UTC.restore();

Autres conseils

In general you can subtract month with such expression:

var d = new Date.UTC(2004, 3, 31);
d.setMonth(d.getMonth()-1);
console.log(d); // Minus one month

With array you can do something like this:

for (var i = 0; i < usdeur.length; i++) {
    var date = usdeur[i][0];
    date.setMonth(date.getMonth()-1);
    usdeur[i][0] = date;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top