Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
171
rated 0 times [  174] [ 3]  / answers: 1 / hits: 32303  / 5 Years ago, wed, january 23, 2019, 12:00:00

How do you format the date in a datapoint's label in Chart.JS?



I've tried this:



this.chart = new Chart(ctx,
{
data: {
labels: timestamps
.map(t => t.toLocaleString([], { month: '2-digit', day: '2-digit', year: '2-digit', hour: '2-digit', minute: '2-digit' })),
datasets: [
{
data: measurements
},
//etc...
]}});


It works, but I get a Moment.JS warning message:




Deprecation warning: value provided is not in a recognized RFC2822 or ISO format... Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release.




Is there a proper way to format dates for data labels in Chart.JS since the method I am using is apparently discouraged?



With labels: timestamps



chart



With labels: timestamps.map(t => t.toLocaleString(...)



chart


More From » chart.js

 Answers
6

I was able to find the answer by inspecting the source HTML file of a sample chart provided by Chart.js.


In order to format the dates properly, one must add the parser and tooltipFormat properties to the axis in question. To fix my example given above:


this.chart = new Chart(ctx,
{
type: 'line',
data: {
labels: timestamps,
datasets: [
{
data: measurements,
}
]
},
options: {
scales: {
xAxes: [ {
display: true,
type: 'time',
time: {
parser: 'MM/DD/YYYY HH:mm',
tooltipFormat: 'll HH:mm',
unit: 'day',
unitStepSize: 1,
displayFormats: {
'day': 'MM/DD/YYYY'
}
}
}
],
yAxis: [
// etc...
],
}
}
}
);

EDIT (1/17/2023)


The sample chart that I linked initially has been removed from the Chart.js documentation. Here's their latest link regarding time scales: Time Cartesian Axis | Chart.js


[#52727] Friday, January 18, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trayvon

Total Points: 35
Total Questions: 117
Total Answers: 88

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;