Search code examples
javascriptjqueryhighchartsutc

How to subtract one month from each month in a Date.UTC Array with jQuery


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.


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();