Chart.js v2 格式化时间标签
Chart.js v2 formatting time labels
我有图表,用户可以在其中输入不同的时间跨度范围,以获得所需的图表结果集。根据图表的范围,时间的格式应该不同。例如,查看一个 10 分钟长的图表,您可能会看到格式为 HH:MM 的时间线上的内容,但对于一个月长的图表来说这没有意义,格式会使mm/dd 的格式更有意义。
返回数据集时,我有开始时间戳(unix ts)和结束时间戳(也是 unix ts)。
Chart.js 是否有工具能够通过转换我上面的时间戳来帮助做出有关格式化时间标签的明智决策?我是否需要使用自定义算法编写回调来手动确定图形和标签的时间戳?
如果需要一个类似于以下内容的手动算法,则需要一些代码来涵盖很多用例:
if (timespan > 86400 * 30)
{
// create format code for month
}
else if (timespan > 86400 * 5)
{
// weekly format
}
else if ( ... ) {}
Chart.js 有更好的方法吗?
来自Chart.js time axis documentation:
When building its ticks, it will automatically calculate the most comfortable unit base on the size of the scale.
这似乎运作良好,如下面的两个图表所示,第一个的范围为 10 分钟,第二个的范围为 10 天:
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>
您可以pass in display formats 为各种单位(分钟、天、月等)自动获取您想要的缩放比例和格式。
我有图表,用户可以在其中输入不同的时间跨度范围,以获得所需的图表结果集。根据图表的范围,时间的格式应该不同。例如,查看一个 10 分钟长的图表,您可能会看到格式为 HH:MM 的时间线上的内容,但对于一个月长的图表来说这没有意义,格式会使mm/dd 的格式更有意义。
返回数据集时,我有开始时间戳(unix ts)和结束时间戳(也是 unix ts)。
Chart.js 是否有工具能够通过转换我上面的时间戳来帮助做出有关格式化时间标签的明智决策?我是否需要使用自定义算法编写回调来手动确定图形和标签的时间戳?
如果需要一个类似于以下内容的手动算法,则需要一些代码来涵盖很多用例:
if (timespan > 86400 * 30)
{
// create format code for month
}
else if (timespan > 86400 * 5)
{
// weekly format
}
else if ( ... ) {}
Chart.js 有更好的方法吗?
来自Chart.js time axis documentation:
When building its ticks, it will automatically calculate the most comfortable unit base on the size of the scale.
这似乎运作良好,如下面的两个图表所示,第一个的范围为 10 分钟,第二个的范围为 10 天:
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>
您可以pass in display formats 为各种单位(分钟、天、月等)自动获取您想要的缩放比例和格式。