Highcharts展示时间序列数据时X轴日期全部显示1 Jan的修复问题
X轴所有标签固定显示1 Jan的核心原因是Highcharts的datetime类型坐标轴要求传入毫秒级Unix时间戳,但你后端返回的是秒级Unix时间戳,数值差了1000倍,导致所有时间都被识别为1970年1月的时间,就会固定显示1 Jan。
方法1:后端处理(推荐)
后端输出数据时直接将时间字段转换为毫秒级Unix时间戳,前端无需额外修改代码即可正常渲染。
方法2:前端处理
如果不方便修改后端接口,可在前端解析数据后批量转换时间单位,修改你的JS代码如下:
var credit = '<?php echo (isset($credit))?$credit:0; ?>' // 新增数据转换逻辑 const parsedCredit = JSON.parse(credit); const formattedData = parsedCredit.map(item => [item[0] * 1000, item[1]]); Highcharts.chart('transactionId', { chart: { type: 'spline' }, title: { text: 'Snow depth at Vikjafjellet, Norway' }, subtitle: { text: 'Irregular time data in Highcharts JS' }, xAxis: { type: 'datetime', // 可根据你的数据时间跨度补全格式配置,显示更合理 dateTimeLabelFormats: { day: '%e %b', month: '%e. %b', year: '%b %Y' }, title: { text: 'Date' } }, yAxis: { title: { text: 'Snow depth (m)' }, min: 0 }, tooltip: { headerFormat: '<b>{series.name}</b><br>', pointFormat: '{point.x:%e. %b}: {point.y:.2f} m' }, plotOptions: { series: { marker: { enabled: true } } }, colors: ['#6CF', '#39F', '#06C', '#036', '#000'], series: [{ name: "Winter 2016-2017", // 替换为转换后的格式化数据 data: formattedData }], responsive: { rules: [{ condition: { maxWidth: 500 }, chartOptions: { plotOptions: { series: { marker: { radius: 2.5 } } } } }] } });
内容的提问来源于stack exchange,提问作者shekwo
相关产品推荐
相关产品推荐

