首页 > 解决方案 > chart.js 按顺序显示时间

问题描述

我想将数组的 x 值显示为时间戳。x 值由 x = Date.now() 生成

var test = {
    "datasets": [{
        "data": [{
            "x": 1609753734252,
            "y": 44.82420388241937
        }, {
            "x": 1609753735263,
            "y": 46.02068615892796
        }, {
            "x": 1609753741254,
            "y": 53.21622091958411
        }]
    }, {
        "data": [{
            "x": 1609753734252,
            "y": 129.77634259930292
        }, {
            "x": 1609753735263,
            "y": 129.86789675071483
        }, {
            "x": 1609753741254,
            "y": 129.9137373479274
        }]
    },
    "labels": [1609753734252, 1609753735263, 1609753741254]
}

选项

    var config = {
        type: 'line',
        options: {
            responsive: true,
            responsiveAnimatinDuration: 500,
            animation: {
                duration: 0
            },
            elements: {
                point: {
                    radius: 0
                },
                line: {
                    borderWidth: 2,
                    fill : false
                }
            },
            legend : {
                display : false
            },
            scales: {
                xAxes: [{
                    type : 'time',
                    time : {
                        format : "HH:MM",
                        unit : "hour"
                    }
                }]
            }
        }
    };

javascript代码:

    config.data = test; 
    window.myLine = new Chart(ctx.getContext('2d'), config);

我想以 hh:mm 格式显示时间?怎么了?

数据将在 500 毫秒内全部更新。我可以隐藏过渡吗?

标签: javascriptchart.js

解决方案


您能否尝试文档中提到的以下方式来格式化日期 https://www.chartjs.org/docs/latest/axes/cartesian/time.html#display-formats

我尝试了以下方法:

            scales: {
                xAxes: [{
                    type: 'time',
                    time: {
                        displayFormats: {
                            second: 'hh:mm:ss'
                        }
                        // unit : 'minute'
                    }
                }]

现在我得到了从 1971 年到今天的所有年份。但我想让 x 缩放设置为自动。如果没有 displayFormat,所有时间都会显示。但不幸的是,只要 int。

我也用“单位”试过。之后我得到一个例外:isAMomemtObject


推荐阅读