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

基于Chart.js从DataTable日期列绘制项目每日频次折线图报错求助

Fixing Moment.js Warning & Implementing Daily Project Issue Counts with Chart.js

Let's break down how to resolve your moment.js warning and build the daily count line chart you need. Here's a step-by-step solution:

First: Understand the Root of the Moment.js Warning

The warning happens because your original code was passing non-date values (like the string 'total project1 issues' and a jQuery collection of table cells) to Chart.js's time scale. Moment.js couldn't parse those as valid dates, hence the fallback to unreliable browser date parsing. We'll fix this by feeding properly formatted date-count pairs to Chart.js.

Step 1: Extract & Process Data from DataTable

Instead of using jQuery selectors to grab columns, use DataTable's API to reliably get all row data. We'll group entries by project and date (truncated to YYYY-MM-DD):

const table = $('#datatable').DataTable();
const rows = table.rows().data().toArray(); // Get all rows as an array of arrays

// Initialize objects to track counts and unique dates
const projectDailyCounts = {};
const allUniqueDates = new Set();

// Process each row
rows.forEach(row => {
  // Adjust indices to match your actual table columns:
  const projectName = row[1]; // Example: software name column (zero-based index)
  const fullDateString = row[5]; // Example: 6th column (zero-based index 5)
  
  // Parse date to YYYY-MM-DD format (ignores time for daily counts)
  const date = moment(fullDateString).format('YYYY-MM-DD');
  allUniqueDates.add(date);
  
  // Initialize project entry if it doesn't exist
  if (!projectDailyCounts[projectName]) {
    projectDailyCounts[projectName] = {};
  }
  
  // Increment count for this date
  projectDailyCounts[projectName][date] = (projectDailyCounts[projectName][date] || 0) + 1;
});

// Sort dates chronologically for the chart x-axis
const sortedDates = Array.from(allUniqueDates).sort((a, b) => moment(a).diff(moment(b)));

Step 2: Prepare Chart.js Datasets

Convert the grouped data into datasets that Chart.js can use. Each project gets its own line with unique colors:

// Define color palette for different projects
const projectColors = [
  { bg: 'rgba(255, 99, 132, 0.2)', border: 'rgba(255, 99, 132, 1)' },
  { bg: 'rgba(54, 162, 235, 0.2)', border: 'rgba(54, 162, 235, 1)' },
  { bg: 'rgba(255, 206, 86, 0.2)', border: 'rgba(255, 206, 86, 1)' },
  { bg: 'rgba(75, 192, 192, 0.2)', border: 'rgba(75, 192, 192, 1)' }
];

// Build datasets for each project
const datasets = Object.entries(projectDailyCounts).map(([projectName, dateCounts], index) => {
  // Create data points in order of sorted dates (fill 0 for days with no issues)
  const dataPoints = sortedDates.map(date => ({
    x: date,
    y: dateCounts[date] || 0
  }));
  
  const color = projectColors[index % projectColors.length];
  
  return {
    label: `${projectName} Issues`,
    data: dataPoints,
    backgroundColor: color.bg,
    borderColor: color.border,
    borderWidth: 1,
    fill: false // Disable filled area under the line (optional)
  };
});

Step 3: Render the Chart

Configure Chart.js with the time scale properly set up (no more moment.js warnings!):

const ctx = document.getElementById('myChart');
new Chart(ctx, {
  type: 'line',
  data: { datasets: datasets },
  options: {
    responsive: true,
    maintainAspectRatio: false,
    scales: {
      x: {
        type: 'time',
        time: {
          unit: 'day',
          displayFormats: { day: 'YYYY-MM-DD' }
        },
        title: { display: true, text: 'Date' }
      },
      y: {
        beginAtZero: true,
        title: { display: true, text: 'Number of Issues' }
      }
    }
  }
});

Note for Chart.js v2 Users

If you're using an older version of Chart.js, adjust the scales syntax to use arrays:

scales: {
  xAxes: [{
    type: 'time',
    time: { unit: 'day', displayFormats: { day: 'YYYY-MM-DD' } },
    title: { display: true, text: 'Date' }
  }],
  yAxes: [{
    ticks: { beginAtZero: true },
    title: { display: true, text: 'Number of Issues' }
  }]
}

Key Fixes & Improvements

  • Valid Date Parsing: We use moment() on the ISO-formatted date strings directly, which eliminates the deprecation warning.
  • Daily Grouping: Truncating dates to YYYY-MM-DD ensures we count issues per calendar day.
  • Dynamic Datasets: Automatically creates a line for every project in your table, no hardcoding needed.
  • Consistent X-Axis: Sorted dates ensure the chart displays chronologically, even if some projects have gaps in their data.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 14:43:13