Google 注释图表日期无效,或日期和时间错误

问题描述 投票:0回答:1

我在格式化 Google 注释图表的日期列时遇到问题。我正在关注此链接https://developers.google.com/chart/interactive/docs/gallery/annotationchart

我的注释图表数据

 var init_data = [["Week","A","A Title","A Annot","B","B Title","B Annot"],
["2022-05-01T18:30:00.000Z",10,"A","AAA",1984,"B","BBB"],
["2022-05-08T18:30:00.000Z",36,"A","AAA",150,"B","BBB"],
["2022-05-15T18:30:00.000Z",30,"A","AAA",199,"B","BBB"],
["2022-05-22T18:30:00.000Z",33,"A","AAA",184,"B","BBB"],
["2022-05-29T18:30:00.000Z",20,"A","AAA",161,"B","BBB"],
["2022-06-05T18:30:00.000Z",37,"A","AAA",172,"B","BBB"],
["2022-06-12T18:30:00.000Z",22,"A","AAA",151,"B","BBB"]]

我使用下面的函数转换为 mm/dd/yyyy 格式

function convertdate(date) {
        date = new Date(date);
        //console.log(date);
        let year = date.getFullYear();
        let month = (1 + date.getMonth()).toString().padStart(2, '0');
        let day = date.getDate().toString().padStart(2, '0');         
        return month + '/' + day + '/' + year;
        }

应用上述函数我的数据看起来像这样


var data = [['Week','A','A Title','A Annot','B','B Title','B Annot'],
['05/01/2022',10,'A','AAA',1984,'B','BBB'],
['05/08/2022',36,'A','AAA',150,'B','BBB'],
['05/15/2022',30,'A','AAA',199,'B','BBB'],
['05/22/2022',33,'A','AAA',184,'B','BBB'],
['05/29/2022',20,'A','AAA',161,'B','BBB'],
['06/05/2022',37,'A','AAA',172,'B','BBB'],
['06/12/2022',22,'A','AAA',151,'B','BBB']]

我将以上数据传递给 Array to DataTable 函数

var chart_data = google.visualization.arrayToDataTable(data);
          var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));

          var options = {
            displayAnnotations: true
          };

          chart.draw(chart_data, options);

它在浏览器中抛出错误(Google)

第一列必须包含日期,或日期和时间。

我尝试使用 new Date() 它给了我类似的日期格式

Mon Oct 09 2023 00:00:00 GMT+0530 (India Standard Time) // This throws same error as well

如何设置 Google 注释图表的日期列格式。

javascript date datetime google-visualization
1个回答
0
投票

下面的解决方案通过使用 Chart Wrapper 函数和 RegEx 函数将字符串转换为日期对我有用。

创建一个DataTable,将输出数组推送到dataTable。

var data = new google.visualization.DataTable();
data.addColumn('date', 'Week');
data.addColumn('number', 'A');
data.addColumn('string', 'A Title');
data.addColumn('string', 'A Annot');
data.addColumn('number', 'B');
data.addColumn('string', 'B Title');
data.addColumn('string', 'B Annot');

for (var i = 0; i < json_arr.length; i++){
     var dt_ = new Date(json_arr[i][0].replace(/(\d{2})-(\d{2})-(\d{4})/,"$2/$1/$3"));            
     data.addRow([dt_,json_arr[i][1],json_arr[i][2],json_arr[i][3],json_arr[i] 
         [4],json_arr[i][5],json_arr[i][6]]);
}

var annot_chart = new google.visualization.ChartWrapper({
            chartType: 'AnnotationChart',
            containerId: 'chart_div',
            dataTable: data,
            options: {
              displayAnnotations: true           
            }         
          });         

          annot_chart.draw(); 
© www.soinside.com 2019 - 2024. All rights reserved.