Chen Kinnrot
Chen Kinnrot

Reputation: 21025

chart.js - display control timescale time zone

I want to configure one chart to have a different timezone (for example I'm in utc+00 and want to display data in utc+01)

Is there a way? according to docs I have to return a moment object, and then date displays according to moment global locale.

Upvotes: 7

Views: 16768

Answers (2)

Barry Smith
Barry Smith

Reputation: 128

I use a callback on the ticks function. That way you only change the label.

import Moment from 'moment';

//...

const options = {
    scales: {
      xAxes: [{
        type: 'time',
        ticks: {
          callback: (label, index, ticks) => {
            const format = 'DD HH'; // Change how you please
            return new Moment(ticks[index].value)
              .utcOffset(this.timeZoneOffsetSeconds / 60)
              .format(format);
          }
        }
      }]
    },
    // other options removed for clarity
  };
  
this.chart = new Chart(chartElem, {
  options: options,
  // other parameters removed for clarity
});

Note on the example: Moment is deprecated, apparently there are better libraries out there but that's what I have in my codebase so...

Upvotes: 2

Alan S
Alan S

Reputation: 439

In the time configuration options specify parser as a function:

                scales: {
                    xAxes: [{
                        type: 'time',
                        time: {
                            unit: 'hour',
                            min: minDate,
                            max: maxDate,
                            displayFormats: {
                                hour: 'HH'
                            },
                            parser: function (utcMoment) {
                                return utcMoment.utcOffset('+0100');
                            }                
                        }
                    }]

As well as converting the chart values this will also apply to the min/max values of the x axis.

This assumes your min/max values and label array is populated with moment objects. If dealing with date objects then the function needs to convert the date to a moment first.

parser: function(date) {
    return moment(date).utcOffset('+0100');
}

Upvotes: 7

Related Questions