Chart.js X轴日期时间显示异常?附相关代码示例
Hey there, I can spot the main issue right away, plus a couple of tweaks you'll need to get your datetime axis working properly. Let's break this down step by step:
1. The Critical Mistake: Unquoted Dates
Your labels array has dates written like 2018-03-28 — in JavaScript, this isn't treated as a string date, it's evaluated as an arithmetic expression (2018 minus 3 minus 28 = 1987). That's why your X-axis is showing weird numeric values instead of dates!
First, wrap every date in quotes to turn them into valid date strings:
labels: ["2018-03-28","2018-03-29","2018-03-30","2018-03-31","2018-04-01",...],
2. Configure Chart.js to Recognize Datetime Axis
Even with quoted dates, Chart.js will treat them as plain strings by default. To make the X-axis behave like a proper datetime axis, add a scales configuration to your chart options:
Here's the full corrected script:
<script> var ctx = document.getElementById("chart0"); var myChart = new Chart(ctx, { type: 'line', data: { labels: ["2018-03-28","2018-03-29","2018-03-30","2018-03-31","2018-04-01","2018-04-02","2018-04-03","2018-04-04","2018-04-05","2018-04-06","2018-04-07","2018-04-08","2018-04-09","2018-04-10","2018-04-11","2018-04-12","2018-04-13","2018-04-14","2018-04-15","2018-04-16","2018-04-17","2018-04-18","2018-04-19","2018-04-20","2018-04-21","2018-04-22","2018-04-23","2018-04-24","2018-04-25","2018-04-26","2018-04-27"], // Don't forget your datasets here! datasets: [{ label: 'Your Data Series', data: [/* your corresponding data values here */], borderColor: '#your-color', fill: false }] }, options: { scales: { x: { type: 'time', time: { parser: 'YYYY-MM-DD', // Match your date string format unit: 'day', // Show ticks per day displayFormats: { day: 'YYYY-MM-DD' // Format for displaying ticks } }, title: { display: true, text: 'Date' } }, y: { title: { display: true, text: 'Value' } } } } }); </script>
Key Notes:
- Dataset Requirement: I added a placeholder
datasetssection because your original code was missing it — Chart.js needs data to plot! - Time Parser: The
parservalue matches yourYYYY-MM-DDdate format; adjust this if your dates use a different structure. - Axis Customization: Tweak
unitanddisplayFormatsto control how dates are grouped and displayed (e.g., use 'week' instead of 'day' if you want weekly ticks).
That should fix your datetime display issues completely!
内容的提问来源于stack exchange,提问作者Nam Apple

