Search code examples
datetimehighchartsformattingaxis-labels

Format datetime axis in highcharts?


http://jsfiddle.net/LLExL/4537/

Can anyone please help with this date time axis formatting on highcharts. 
I want  Xaxis to show month only once unless the new month begins.
Like 29 April 30 1 May 2 3 4 5 
Any help would be highly appreciated

Solution

  • You can use the xAxis.labels.formatter function to specify exactly what you want to show as xAxis labels:

    labels: {
        formatter: function() {
            var date = new Date(this.value);
            var month = date.toDateString().substring(4,7);
            var day = date.getDate();
    
            if(this.isFirst || day == 1)
                return day + '. ' + month;
    
            return day;
        }
    }
    

    Here's the DEMO.

    EDIT:

    And if your first day of every month doesn't start from 1, you can alter your code like this:

    labels: {
        formatter: function() {
             var dateArray = this.axis.series[0].xData;
             var previousDate = new Date(dateArray[dateArray.indexOf(this.value) - 1]);
             var date = new Date(this.value);
             var month = date.toDateString().substring(4,7);
             var previousMonth = previousDate.toDateString().substring(4,7);
             var day = date.getDate();
    
             if(this.isFirst || (previousMonth != month))
                return day + '. ' + month;
    
             return day;
         }
    }
    

    This way you can check the previous point and if their month didn't match you can return day and month. Else only day. Here's the DEMO.