davidm_uk
davidm_uk

Reputation: 768

Configuring locale with bundled (CDN) chartjs-adapter-date-fns.bundle.min.js?

I'm using Chart.js in client-side HTML with the date-fns adapter (https://github.com/chartjs/chartjs-adapter-date-fns) to allow a time cartesian axis (https://www.chartjs.org/docs/latest/axes/cartesian/time.html).

I'm loading chartjs-adapter-date-fns from the CDN - i.e. my page loads chartjs-adapter-date-fns.bundle.min.js. (I'm not using the import and webpack.)

Is it still possible to configure locale support as per https://github.com/chartjs/chartjs-adapter-date-fns#locale-support-via-scale-options? If so, please can you give me an example of how to access the locale class to pass to adapters.date.locale in the scale options.

Documentation states:

// import date-fns locale:
import {de} from 'date-fns/locale';


// scale options:
{
    adapters: {
        date: {
            locale: de
        }
    }
}

... but import doesn't work in the browser - so how do I get hold of a locale like de?

Upvotes: 6

Views: 4812

Answers (2)

Clemens
Clemens

Reputation: 1

I'm using NuxtJS, but it doesn't really matter. You just have to get the locales into your site. A little bit more on date-fns locales here

Then, in ChartJS options I did it this way and it worked:

const ausgaben = new Chart(ctx, {
    type: 'bar',
    data: {
      backgroundColor: '#fff',
      datasets: [
        {
          label: 'Ausgaben',
          data: app.chartData.first,
          backgroundColor: 'red',
          type: 'bar',
          order: 10
        },
        additionalDataset
      ]
    },

    options: {
      scales: {
        x: {
          type: 'time',
          distribution: 'linear',
          time: {
            unit: 'day'
          },
          adapters: {
            date: {
              locale: de
            }
          },
        }
      }
    }
  })

Upvotes: 0

Jesper
Jesper

Reputation: 1086

I switched to Luxon because i was having trouble with locales when using date-fns. Then it's a simple one liner: luxon.Settings.defaultLocale = "fi";

The luxon library is also great for parsing time, so i recommend using it if possible. More on luxon

Upvotes: 5

Related Questions