Search code examples
javascriptsharepointhighchartsspservices

Can't change date format on Highcharts


I'm trying to change the date format on my x-axis label from "2014-10-05 00:00:00" to "Oct-5"

Reviewing the Highcharts dateTimeLabelFormats API, it looks like I need to add %b-%e to the label, however this doesn't seem to work.

Here is a screenshot of the results I'm currently getting: https://i.sstatic.net/6ziJG.jpg

Here is my code:

$(document).ready(function() {

 var yearmontharray = [];
 var valuesarray = [];

 $().SPServices({
  operation: "GetListItems",
  async: false,
  listName: "List",
  CAMLViewFields: "<ViewFields><FieldRef Name='Date' /><FieldRef Name='values' /></ViewFields>",
  completefunc: function (xData, Status) {
   $(xData.responseXML).SPFilterNode("z:row").each(function() {
    var yearmonth = ($(this).attr("ows_Date"));
    var values = Math.round($(this).attr("ows_values"));

    yearmontharray.push(yearmonth);
    valuesarray.push(values);
   });
   console.log(valuesarray);
   var chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                type: 'line',
                marginRight: 130,
                marginBottom: 25
            },
            title: {
                text: 'Total values',
                x: -20
            },
            subtitle: {
                text: 'This chart shows value from SharePoint',
                x: -20
            },
            xAxis: {
                categories: yearmontharray,
                labels: {
                    overflow: 'justify',
                    type: 'datetime',
                    dateTimeLabelFormats: {
                        day: '%b-%e'
                    }
                }
            },
            yAxis: {
                title: {
                    text: 'values'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'top',
                x: -10,
                y: 100,
                borderWidth: 0
            },
            series: [{
                name: 'values',
                data: valuesarray
            }]
        });

  }
 });
 
 
  
});


Solution

  • The problem is with using categories: categories: yearmontharray, - when you use categories, then xAxis.type is set to category, not datetime.

    So you have a couple of solutions:

    • use formatter for labels, there preprocess your category string to get desired output
    • change your format on backend side, to return categories formatter in a proper way
    • instead of using categories, use datetime axis. More about can be found here.

    In genera, I advice to read about axes(!) in Highcharts. The better you understand library, the better results you will have.