Chart.js v2格式化时间标签 [英] Chart.js v2 formatting time labels

查看:70
本文介绍了Chart.js v2格式化时间标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些图表,用户可以在其中输入不同的时间范围,以便将所需的结果设置为图表。根据图表的范围,时间的格式应该不同。例如,看一个长10分钟的图形,您可能会看到一段时间的格式为HH:MM的内容,但对于一个月的图形却没有意义,因为格式化会更有意义以mm / dd的格式。

I have charts where a user can input a different range of time spans in order to get a desired result set to graph. Depending on the range of the graph, the formatting of the times should be different. As an example, looking at a graph that's 10 minutes long, you'll probably see something along the lines of a time that's formatted HH:MM, but that won't make sense for a month long graph, where formatting would make more sense in the format of mm/dd.

返回数据集时,我有开始时间戳(unix ts)和结束时间戳(unix ts)。

I have the beginning timestamp (unix ts) and the ending timestamp (also unix ts) when a dataset is returned.

Chart.js是否具有能够通过转换上面的时间戳来帮助您明智地决定格式化时间标签的工具?我需要使用自定义算法编写一个回调来手动确定图形和标签的时间戳吗?

Does Chart.js have the tools to be able to help make smart decisions on formatting the time labels by converting the timestamps I have above? Do I need to write a callback with a custom algorithm that determines the timestamp of the graph and label manually?

将需要一些代码来覆盖很多使用案例,如果需要一个手动算法,看起来类似于以下内容:

There would need to be some code to cover a lot of the use cases if a manual algorithm is required that looks something along the lines of:

if (timespan > 86400 * 30)      
{
    // create format code for month 
}
else if (timespan > 86400 * 5)
{
    // weekly format
}
else if ( ... ) {}

有没有更好的方法

推荐答案

来自Chart.js 时间轴文档

From the Chart.js time axis documentation:


建立刻度线时,它将根据秤的大小自动计算最舒适的单位。

When building its ticks, it will automatically calculate the most comfortable unit base on the size of the scale.

tw中显示o在下面的图表中,第一个图表显示的时间为10分钟,第二个图表显示的时间为10天:

This appears to work well as shown in the two charts below, the first with a range of 10 minutes and the second with a range of 10 days:

let now = (new Date()).getTime(),
  minutes = [],
  days = [],
  options = {
    scales: {
      xAxes: [{
        type: 'time'
      }]
    }
  };

for (let i = 0; i < 10; i++) {
  minutes.push({
    x: now + (60000 * i),
    y: 10
  });
  days.push({
    x: now + (86400000 * i),
    y: 10
  });
}

new Chart(document.getElementById('canvas1'), {
  type: 'line',
  data: {
    datasets: [{
      data: minutes
    }]
  },
  options: options
});

new Chart(document.getElementById('canvas2'), {
  type: 'line',
  data: {
    datasets: [{
      data: days
    }]
  },
  options: options
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.min.js"></script>
<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>

您可以为各个单元传递显示格式 (分钟,天,月等)以自动获取所需的缩放比例和格式。

You can pass in display formats for the various units (minute, day, month, etc) to automatically get the scaling and formatting you want.

这篇关于Chart.js v2格式化时间标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆