To generate the labels for your chart with the dates for the last 7 days (including the current day), you can use the Date
object in JavaScript to generate the dates. Here’s an example of how you can modify your code to do that:
// Generate the labels for the chart
var labels = [];
var today = new Date();
for ( var i = 0; i < 7; i++ ) {
// Generate the date for each label by subtracting the number of days from the current date
var date = new Date( today.getFullYear(), today.getMonth(), today.getDate() - i );
labels.push( date.toDateString() );
}
// Use the generated labels in the chart
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: labels, // Use the generated labels here
datasets: [
{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45]
},
{
label: 'My Second dataset',
backgroundColor: 'rgb(255, 43, 122)',
borderColor: 'rgb(255, 45, 122)',
data: [0, 20, 3, 4, 30, 40, 41]
}
]
},
// Configuration options go here
options: {}
});
This code will generate an array of labels with the dates for the last 7 days (including the current day) in the format dayOfWeek month dayOfMonth year
, and use that array as the labels for the chart.
Note: The Date
object in JavaScript uses a zero-based index for months (0 for January, 1 for February, etc.), so make sure to subtract 1 from the month when generating the dates.