[Chartjs]-ChartJS: Translate x axis month to other languages

0👍

I was struggling with the same problem in my Ruby on Rails application.

We don’t use angularjs, but I think the way of using Chart.js is very similar.

I will post the way I managed it to work in Ruby on Rails and polish locale. But you should be able to easy customize the solution to work with Angular.js

  1. Include moment.js locale in the JavaScript bundle apart of moment.js library
//= require moment
//= require moment/pl.js
  1. Add custom displayFormats to make it easier to parse date in callback function. And add callback function to parse and format date again.
options: {
                    ...
                    scales: {
                        xAxes: [{
                            type: 'time',
                            time: {
                              displayFormats: {
                               'hour': 'HH:mm',
                               'day': 'DD-MM-YYYY',
                               'week': 'DD-MM-YYYY',
                               'month': 'DD-MM-YYYY',
                              },
                              unit: '<%= @report.scale %>',
                            },
                            ticks: {
                              callback: function(value, index) {
                                let displayFormats = {
                                  'hour': 'HH:mm',
                                  'day': 'DD-MM-YYYY',
                                  'week': 'YYYY WW',
                                  'month': 'MMMM YYYY',
                                };
                                let unit = '<%= @report.scale %>';
                                let format = displayFormats[unit];
                                return moment(value, 'DD-MM-YYYY').format(format, value);
                              }
                            }
                        }],

For some reason moment.js inside of Chart.js ignores locales. But when calling moment.js again inside of the callback function it works well.

I added guard return for all units other than month. I didn’t want to reparse and reformat dates other than months.

Leave a comment