Chartjs-How to change the Date Format in Chart.js?

0๐Ÿ‘

Try displayFormats:

const chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        scales: {
            x: {
                type: 'time',
                time: {
                    displayFormats: {
                        quarter: 'MMM YYYY'
                    }
                }
            }
        }
    }
});

Chart.js Time Display Formats

0๐Ÿ‘

The x-axis of your bar chart is currently a category axis instead of a time axis. The reason is that options is misplaced, it should not be defined inside the dataset but follow the top level structure of the Chart.js configuration.

With react-chartjs-2, you would define options as a separate object and provide it as follows:

<Bar data={data} options={options} /> 

Once this is is corrected, the display format can be defined according to the Chart.js documentation here.

Please also consider that the time scale requires both, a date library and a corresponding adapter to be present.

0๐Ÿ‘

Change your for loop like below

for (const dataObj of res.data) {
      Cost.push(parseInt(dataObj.Cost));
      const date = new Date(dataObj.StartD);
      No.push(date->toLocaleDateString('en-us',{month:"2-digit", day:"2-digit"));
    }

0๐Ÿ‘

I just figure out the answer. Thanks for helping. I take @terinaoโ€˜s code for references.

Changing the code like this can solve the problem.

 axios.get("http://localhost:3001/api/TranscationRecord/Cost")
    .then(res => {
        console.log(res);
        for(const dataObj of res.data){
            Cost.push(parseInt(dataObj.Cost));
            const d = new Date(dataObj.StartD);
            No.push(d.toLocaleDateString('en-us',{day:"2-digit",month:"2-digit" }));
        }

The result be like:
(I change the colour into blue but they are the same datasets)
The bar chart

Leave a comment