Search code examples
javascripthighchartsdatejs

Having trouble incrementing X axis by Month in Highchart


I am trying to create a graph in high charts where the plot interval is equal to a calendar month (varies per month). I am using date.js which has a function called addMonths which understands the different number of days in a month.

However I am having trouble converting this into something that highcharts understands (appears to be ms).

Does anybody know how I can get this simple POC code to have 1 month intervals on the x axis?

http://jsfiddle.net/uqv23bze/

$(function () {
var data = [];
var d = new Date();

for(var i=0;i<10;i++){
    var x = new Date(d.addMonths(1));        
    data.push([x,i]);
}

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

});


Solution

  • Highcharts support the UTC date format in ms as you said. DateTime can be converted using Date.UTC in javascript:

    var date = new Date(d.addMonths(1));
    var x = Date.UTC(date.getYear() + 1900, date.getMonth(), date.getDate());
    

    Also you have to use tickInterval for xAxis to make sure the intervals are in months:

    tickInterval: 30 * 24 * 3600 * 1000 // (30 days, 24 hours, 3600 seconds, 1000 milliseconds)
    

    Here's the DEMO