How to define chart.js time scale date formats?

Member

by darion , in category: Javascript , 10 months ago

How to define chart.js time scale date formats?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 5 months ago

@darion 

To define time scale date formats in Chart.js, you can use the time scale type on the x-axis. You can configure the date formats using the time options in the x-axis configuration. Here is an example of how to define date formats for the time scale in Chart.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
var chart = new Chart(ctx, {
  type: 'line',
  data: data,
  options: {
    scales: {
      x: {
        type: 'time',
        time: {
          unit: 'day', // display label for every day
          displayFormats: {
            day: 'MM/DD/YYYY', // format for day labels
            week: 'MM/DD/YYYY', // format for week labels
            month: 'MM/YYYY', // format for month labels
            year: 'YYYY' // format for year labels
          }
        }
      }
    }
  }
});


You can customize the date formats by setting the unit property to specify the interval for displaying the labels, and the displayFormats property to define the format for each unit interval. You can use various date formats such as 'MM/DD/YYYY', 'YYYY-MM-DD', 'DD MMM YYYY', etc.


By configuring the date formats for the time scale in Chart.js, you can display the dates in the desired format on the x-axis of your chart.