我想使用C3.js
格式的日期和格式字符串2015-09-17 18:20:34
显示时间序列图表'%Y-%m-%d %H:%M:%S'
,但无法解析。
我的代码:
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'times',
columns: [
['times','2015-09-17 18:20:34','2015-09-17 18:25:42','2015-09-17 18:30:48'],
['data','1539','1546','1546','1550']
]
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d %H:%M:%S'
}
}
}
});
我收到以下错误:
02:26:44.889 Failed to parse x '2015-09-17 18:20:34' to Date object c3.min.js:1:21943
02:26:44.889 Failed to parse x '2015-09-17 18:25:42' to Date object c3.min.js:1:21943
02:26:44.890 Failed to parse x '2015-09-17 18:30:48' to Date object c3.min.js:1:21943
02:26:44.890 Failed to parse x '2015-09-17 18:20:34' to Date object c3.min.js:1:21943
02:26:44.891 Failed to parse x '2015-09-17 18:25:42' to Date object c3.min.js:1:21943
02:26:44.892 Failed to parse x '2015-09-17 18:30:48' to Date object c3.min.js:1:21943
如果我省略了数据和格式中的时间,但是我也需要时间。
答案 0 :(得分:29)
我找到了解决问题的方法:
axis
对象中的格式只是定义日期的显示方式。如果要指定日期解析的格式,则必须在xFormat
对象中使用data
。
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'times',
xFormat: '%Y-%m-%d %H:%M:%S', // how the date is parsed
columns: [
['times','2015-09-17 18:20:34','2015-09-17 18:25:42','2015-09-17 18:30:48'],
['data','1539','1546','1546','1550']
]
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d %H:%M:%S' // how the date is displayed
}
}
}
});
答案 1 :(得分:2)
还有另一种将日期传递给c3时间序列数组的方法。您可以在将日期字符串转换为c3之前将其转换为Javascript Date object。
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'times',
xFormat: '%Y-%m-%d %H:%M:%S', // how the date is parsed
columns: [
['times',new Date('2015-09-17 18:20:34'),new Date('2015-09-17 18:25:42'),new Date('2015-09-17 18:30:48')],
['data','1539','1546','1546','1550']
]
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d %H:%M:%S' // how the date is displayed
}
}
}
});
如果您在将日期字符串转换为日期对象时遇到困难(例如2016-01-01T00:00:00Z),您还可以使用momentjs来解析日期字符串。
var momentjsobject = moment('2016-05-06T00:00:00Z');
var dateObject = new Date(momentjsobject.format('YYYY-MM-DD HH:mm:ss'));