【发布时间】:2013-10-14 17:46:28
【问题描述】:
我正在使用 Google 图表来显示来自 Google 电子表格的一些数据。这是我的一段代码。
var queryurl = <link to the Google spreadsheet>;
function drawVisualization() {
var query = new google.visualization.Query(queryurl);
// Send the query with a callback function.
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
// Prepare the data
var data = response.getDataTable();
var table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'chart2',
'options': {
'showRowNumber': 'true'
}
});
}
其中一列实际上包含日期,格式为日/月/年,例如2013 年 10 月 15 日。但是,当我尝试通过单击标题对这个特定列进行排序时,排序是通过将每个日期视为一个字符串来执行的,例如,如果三个日期是 01/02/1999、01/03/1999和 01/09/1997 那么排序顺序(升序)是 01/02/1999、01/03/1999 和 01/09/1997,而不是 01/09/1997、01/02/1999、01 的正确顺序/03/1999。
我的问题是:有什么方法可以确保日期上下文中的排序是正确的?例如,我是否需要指定每列中包含的数据类型(这当然是在原始 Google 电子表格中完成的)?
提前致谢!
【问题讨论】:
-
猜测一下,您的“日期”实际上是字符串,而不是 Date 对象。检查日期列的内容,看看是否是这种情况,例如:添加行
console.dir(data.getValue(0, <date column index>));,在Firefox 或Chrome 中打开页面,并查看开发人员控制台以查看输出内容。如果是“01/02/1999”这样的字符串,则需要将字符串转换为日期对象。 -
这也是我怀疑的,但感谢您提供有关如何验证它的提示。因此,1/1/1997 形式的日期被视为字符串。由于我将表格作为单个对象导入,如何更改单个列的“类型”?
-
您必须使用 DataView 将字符串转换为日期。我会发布一个详细的答案。
标签: sorting google-visualization