格式化Google Charts日期时间轴标签的时区

Nei*_*eil 9 javascript timezone google-visualization

我正在使用GoogleCharts沿一个轴绘制一个'datetime'类型的折线图.我想格式化轴标签,以便它们在指定的时区而不是默认的浏览器时区显示时间.

通过阅读文档,有一个DateFormat对象,可以提供'timeZone'选项,然后使用相应的DataTable列调用以格式化该列中的所有单元格.我注意到,如果将DataTable其绘制为表格,则执行此操作会导致格式正确的值.但是,相同的格式不适用于图表上的轴标签,如LineChartBar.

这是我的代码:

var dataTable = new google.visualization.DataTable();

dataTable.addColumn('datetime', 'Time');
dataTable.addColumn('number', 'Wolves');
dataTable.addRows([
  [new Date(2020, 1, 1, 12), 1],
  [new Date(2020, 1, 1, 13), 3]
]);

// Create DateFormat with a timezone offset of -4
var dateFormat = new google.visualization.DateFormat({formatType: 'long', timeZone: -4});

// Format the first column
dateFormat.format(dataTable, 0);

dataTable.getFormattedValue(0, 0); // "February 1, 2020 at 8:00:00 AM UTC-4"

var table = new google.visualization.Table(document.getElementById('wolf_table'));
table.draw(dataTable);

var lineChart = new google.visualization.LineChart(document.getElementById('wolf_chart'));
lineChart.draw(dataTable);
Run Code Online (Sandbox Code Playgroud)

这是结果图表:

带有日期时间轴的图表

请注意表格如何在相关单元格中显示正确格式化的时间,而折线图轴显示浏览器时间(在这种情况下为GMT).

有没有办法改变折线图轴标签的时区格式?有什么我可能会失踪?

Whi*_*Hat 2

使用hAxis.ticks 配置选项提供轴标签

一旦数据被格式化DateFormat

构建一个包含要显示的标签的数组

使用对象表示法为每个标签 提供值 ( v:) 和格式化值 ( )f:

// Set X-Axis Labels
var xTicks = [];
for (var i = 0; i < dataTable.getNumberOfRows(); i++) {
  xTicks.push({
    v: dataTable.getValue(i, 0),
    f: dataTable.getFormattedValue(i, 0)
  });
}
Run Code Online (Sandbox Code Playgroud)

如果您不一定需要格式化整个dataTable
或者您想使用 中不存在的标签dataTable
请使用formatValue上的方法DateFormat

// Set X-Axis Labels
var xTicks = [];
for (var i = 0; i < dataTable.getNumberOfRows(); i++) {
  xTicks.push({
    v: dataTable.getValue(i, 0),
    f: dateFormat.formatValue(dataTable.getValue(i, 0))
  });      
}

/*** OR ***/      

// custom date, not in dataTable
var customDate = new Date(2016, 9, 4, 22, 7, 7);
xTicks.push({
  v: customDate,  
  f: dateFormat.formatValue(customDate)
});
Run Code Online (Sandbox Code Playgroud)

请参阅以下工作片段...

// Set X-Axis Labels
var xTicks = [];
for (var i = 0; i < dataTable.getNumberOfRows(); i++) {
  xTicks.push({
    v: dataTable.getValue(i, 0),
    f: dataTable.getFormattedValue(i, 0)
  });
}
Run Code Online (Sandbox Code Playgroud)
// Set X-Axis Labels
var xTicks = [];
for (var i = 0; i < dataTable.getNumberOfRows(); i++) {
  xTicks.push({
    v: dataTable.getValue(i, 0),
    f: dateFormat.formatValue(dataTable.getValue(i, 0))
  });      
}

/*** OR ***/      

// custom date, not in dataTable
var customDate = new Date(2016, 9, 4, 22, 7, 7);
xTicks.push({
  v: customDate,  
  f: dateFormat.formatValue(customDate)
});
Run Code Online (Sandbox Code Playgroud)