【问题标题】:Chart x axis displays in timestamp instead of dates Chart.js图表 x 轴以时间戳而不是日期显示 Chart.js
【发布时间】:2019-11-11 23:39:11
【问题描述】:

我正在使用图表 js 绘制 json 图表。即使我将格式设置为日期,我仍然会得到时间戳。我希望有一个人可以帮助我。顺便说一句,正在从 firebase 检索数据。我附上我正在使用的代码。

提前致谢。

输出:

期望的输出:

代码:

            var currentDate= val.date; //Extracting the date value in dd/mm/yyyy format from the mentioned text box

我从 firebase 获取数据

                     //Printing the extracted date value before making the change
                    var newDate = currentDate.split('/'); //Splitting the extracted date value using the delimiter /, which is the seperator used in the date value         
                    currentDate = newDate[1] + "/" + newDate[0] + "/" + newDate[2];//Constructing a new date value (string) using the splitted values.

我将其格式化为 MMDDYYYY

var dateObject = new Date(currentDate);

然后改成日期数据类型

var data_point={
  x:dateObject,
  y:parseFloat(val.sa_quantity)
};
datapoints.push(data_point);

我将所有更改的数据添加到用于绘制数据的数组中

var chartData = [];
      var ctxR = document.getElementById("data_chart").getContext('2d');
      var myChart = new Chart(ctxR, {
        type: 'scatter',
        data: {
          labels:dates,
          datasets: [{
            label: 'Predicted Sales($)',
            data: datapoints
          }]
        },
        responsive: true,
            title:{
                display: true,
                text:"Chart.js Time Scale"
            },
            scales:{
                xAxes: [{
                  type: 'time',
                  time: {
                    displayFormats: {
                      'millisecond': 'MMM DD',
                      'second': 'MMM DD',
                      'minute': 'MMM DD',
                      'hour': 'MMM DD',
                      'day': 'MMM DD',
                      'week': 'MMM DD',
                      'month': 'MMM DD',
                      'quarter': 'MMM DD',
                      'year': 'MMM DD',
                    },
                    round: 'day',
                    unit: 'day',
                  }
                }]
            }
        });
        myChart.update();

【问题讨论】:

  • 我有同样的问题,你能分享你的工作代码吗?

标签: javascript web charts chart.js chart.js2


【解决方案1】:

您必须更改显示格式。 chart.js 喜欢 unix,人们喜欢日期字符串。 你应该添加类似这个函数来显示你的日期:

function getTimeString(date) {
  var day = date.getDate();
  var month = date.getMonth() + 1;
  var year = date.getFullYear();

  return day + '/' + month + '/' + year;
}

每当我在 chart.js 中使用时间刻度时,我都会添加 moment.js,因为它更强大。但这对于 web 应用来说可能有点过头了。

【讨论】:

  • 你如何实现这个?我有完全相同的问题
猜你喜欢
  • 1970-01-01
  • 2015-06-19
  • 1970-01-01
  • 2016-02-16
  • 1970-01-01
  • 1970-01-01
  • 2020-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多