谷歌timeLine图表

时间:2018-04-25 14:55:11

标签: javascript datetime charts google-visualization timeline

我试图创建一个时间轴图表但我面临日期格式的问题我得到错误

  

(值无效日期与列索引2中的类型日期不匹配)

这是我的代码

google.charts.load("current", { packages: ["timeline"] });
google.charts.setOnLoadCallback(initTimeLineChart);

function initTimeLineChart(obj) {
    console.log(obj)
    var container = document.getElementById('timeline1');
    var chart = new google.visualization.Timeline(container);
    var dataTable = new google.visualization.DataTable();
    dataTable.addColumn({ type: 'string', id: 'DriverName' });
    dataTable.addColumn({ type: 'string', id: 'Activity' });
    dataTable.addColumn({ type: 'date', id: 'Start' });
    dataTable.addColumn({ type: 'date', id: 'End' });
    var datas = '';
    $.each(obj,
        function (i, v) {

            if (i === 0) {
                datas = '["' + v.DriverName + '", "' + v.Activity + '","' + convert(v.Start) + '","' + convert(v.End) + '"]';
            } else {
                datas = datas + ',["' + v.DriverName + '", "' + v.Activity + '","' + convert(v.Start) + '","' + convert(v.End) + '"]';
            }

        });
    datas = '[' + datas + ']';
    console.log(datas);
    dataTable.addRows(JSON.parse(datas));
    var options = {
        timeline: { singleColor: '#8d8' }
    };

    chart.draw(dataTable, options);
}
function convert(str) {
    var month, day, year, hours, minutes, seconds;
    var date = new Date(str),
        month = ("0" + (date.getMonth() + 1)).slice(-2),
        day = ("0" + date.getDate()).slice(-2);
    hours = ("0" + date.getHours()).slice(-2);
    minutes = ("0" + date.getMinutes()).slice(-2);
    year = ("20 "+date.getYear());
    console.log(date);
    return new Date(year, 0, day, hours, minutes, 0);
}

1 个答案:

答案 0 :(得分:0)

而不是从字符串构建数组,
只需使用实际数组,以及addRow mtheod

替换所有这些......

var datas = '';
$.each(obj,
    function (i, v) {

        if (i === 0) {
            datas = '["' + v.DriverName + '", "' + v.Activity + '","' + convert(v.Start) + '","' + convert(v.End) + '"]';
        } else {
            datas = datas + ',["' + v.DriverName + '", "' + v.Activity + '","' + convert(v.Start) + '","' + convert(v.End) + '"]';
        }

    });
datas = '[' + datas + ']';
console.log(datas);
dataTable.addRows(JSON.parse(datas));

与......

$.each(obj, function (i, v) {
  dataTable.addRow([
    v.DriverName,
    v.Activity,
    convert(v.Start),
    convert(v.End)
  ]);
});