How to format x-axis time scale values in Chart.js v2
I am able to format the tooltips when I hover over a datapoint on a line chart via options.scales.xAxes.time.tooltipFormat
, but I can't seem to do it for the x-axis tick lables. My data.labels
is an array of moment objects. They display as "MMM DD, YYYY"
(e.g. Feb 23, 2012), but I want to drop the year.
Solution 1:
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/
Solution 2:
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'});
},
},