[Chartjs]-How to format x-axis time scale values in Chart.js v2

113👍

Just set all the selected time unit’s displayFormat to MMM DD

options: {
  scales: {
    xAxes: [{
      type: 'time',
      time: {
        displayFormats: {
           'millisecond': 'MMM DD',
           'second': 'MMM DD',
           'minute': 'MMM DD',
           'hour': 'MMM DD',
           'day': 'MMM DD',
           'week': 'MMM DD',
           'month': 'MMM DD',
           'quarter': 'MMM DD',
           'year': 'MMM DD',
        }
        ...

Notice that I’ve set all the unit’s display format to MMM DD. A better way, if you have control over the range of your data and the chart size, would be force a unit, like so

options: {
  scales: {
    xAxes: [{
      type: 'time',
      time: {
        unit: 'day',
        unitStepSize: 1,
        displayFormats: {
           'day': 'MMM DD'
        }
        ...

Fiddle – http://jsfiddle.net/prfd1m8q/

26👍

as per the Chart js documentation page tick configuration section. you can format the value of each tick using the callback function. for example I wanted to change locale of displayed dates to be always German. in the ticks parts of the axis options

ticks: {
    callback: function(value) { 
        return new Date(value).toLocaleDateString('de-DE', {month:'short', year:'numeric'}); 
    },
},

2👍

I had a different use case, I want different formats based how long between start and end time of data in graph. I found this to be simplest approach

let xAxes = {
    type: "time",
    time: {
        displayFormats: {
            hour: "hA"
        }
    },
    display: true,
    ticks: {
        reverse: true
    },
    gridLines: { display: false }
}
// if more than two days between start and end of data,  set format to show date,  not hrs
if ((parseInt(Cookies.get("epoch_max")) - parseInt(Cookies.get("epoch_min"))) > (1000 * 60 * 60 * 24 * 2)) {
    xAxes.time.displayFormats.hour = "MMM D";
}

0👍

You could format the dates before you add them to your array. That is how I did. I used AngularJS

//convert the date to a standard format
var dt = new Date(date);
//take only the date and month and push them to your label array

$rootScope.charts.mainChart.labels.push(dt.getDate() + "-" + (dt.getMonth() + 1));

Use this array in your chart presentation

Leave a comment