You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Chart.js中根据时间差条件性切换X轴标签显示格式

实现Chart.js根据日期差动态格式化X轴标签

步骤1:计算日期时间差

先获取起始、结束日期并计算时间差,判断是否超过1年:

// 获取日期输入框的标准格式值(建议输入框用type="date")
const startDate = new Date(document.getElementById('start-date').value);
const endDate = new Date(document.getElementById('end-date').value);

// 计算时间差并转成年份近似值
const timeDiff = Math.abs(endDate - startDate);
const yearDiff = timeDiff / (1000 * 60 * 60 * 24 * 365);
const isOverYear = yearDiff > 1;

步骤2:配置Chart.js的X轴标签回调

在图表配置的X轴ticks.callback中,根据时间差切换格式化逻辑:

const chart = new Chart(document.getElementById('myChart'), {
  type: 'line',
  data: {
    labels: ['2021-01-25', '2021-06-25', '2021-11-25', '2022-05-25', '2023-05-25'], // 示例日期数据集
    datasets: [{
      label: '数据趋势',
      data: [12, 19, 3, 5, 2],
      borderColor: 'rgb(75, 192, 192)',
      tension: 0.1
    }]
  },
  options: {
    scales: {
      x: {
        ticks: {
          callback: function(value, index) {
            const date = new Date(this.chart.data.labels[index]);
            if (isOverYear) {
              // 超过1年:输出 "May 2020" 或 "May '21" 格式
              const month = date.toLocaleString('en-US', { month: 'long' });
              const year = date.getFullYear();
              return `${month} ${year.toString().slice(-2)}`; // 可按需调整为带单引号的格式
            } else {
              // 未超过1年:输出 "25 Jan" 格式
              const day = date.getDate();
              const month = date.toLocaleString('en-US', { month: 'short' });
              return `${day} ${month}`;
            }
          }
        }
      }
    }
  }
});

步骤3:监听日期输入变化,实时更新图表

当用户修改日期时,重新计算时间差并刷新图表:

// 给日期输入框绑定变更事件
document.getElementById('start-date').addEventListener('change', updateChart);
document.getElementById('end-date').addEventListener('change', updateChart);

function updateChart() {
  // 重新计算时间差
  const startDate = new Date(document.getElementById('start-date').value);
  const endDate = new Date(document.getElementById('end-date').value);
  const timeDiff = Math.abs(endDate - startDate);
  const yearDiff = timeDiff / (1000 * 60 * 60 * 24 * 365);
  window.isOverYear = yearDiff > 1;
  
  // 触发图表更新
  chart.update();
}

注意事项

  • 确保日期输入框使用type="date",这样获取的是标准ISO格式日期,避免解析错误。
  • 年份缩写逻辑可按需调整,比如仅对非当前年显示后两位加单引号。
  • 如果需要精准计算闰年等场景的日期差,可使用date-fns等日期库,原生JS实现足以覆盖大多数常规需求。

内容的提问来源于stack exchange,提问作者Tambua Rex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 18:31:08