
本文详解如何将原始日期字符串数据正确转换为 Highcharts Stock 所需的时间戳格式,并解决 xAxis.categories 在 Stock 图表中失效的核心问题,确保日期轴自动对齐、范围选择器正常工作。
本文详解如何将原始日期字符串数据正确转换为 highcharts stock 所需的时间戳格式,并解决 `xaxis.categories` 在 stock 图表中失效的核心问题,确保日期轴自动对齐、范围选择器正常工作。
Highcharts Stock 与基础版 Highcharts 的核心差异之一在于:它专为时间序列分析设计,强制要求 x 轴为时间型(datetime)而非分类型(category)。一旦你调用 Highcharts.stockChart(),xAxis.categories 将被完全忽略——这正是你截图中图表空白、日期未渲染的根本原因。
✅ 正确做法:使用时间戳 + datetime xAxis
Highcharts Stock 默认将 x 轴识别为毫秒级时间戳(Unix epoch,单位:ms),并自动启用智能时间轴(含缩放、范围选择器、滚动等)。因此,你必须:
- 后端返回标准 ISO 或可解析日期字符串(如 "2024-06-15"、"2024-06-15 14:30:00");
- 前端将日期字符串安全转为毫秒时间戳;
- 移除 xAxis.categories,改用 xAxis.type = 'datetime'(默认即生效);
- 系列数据采用 [timestamp, value] 二维数组格式。
以下是修正后的关键代码段(已适配你的 PHP + jQuery 环境):
function datagrafico(base_url) {
$.ajax({
url: base_url + "index.php/Admin/getDataDias",
type: "POST",
dataType: "json",
success: function(data) {
const seriesData = data.map(item => {
// 安全解析日期:兼容 'Y-m-d' 或 'Y-m-d H:i:s' 格式
const dateObj = new Date(item.fecha_actualizacion);
const timestamp = dateObj.getTime(); // 转为毫秒时间戳
const monto = Number(item.monto) || 0;
return [timestamp, monto];
});
graficar(seriesData);
}
});
}
function graficar(seriesData) {
Highcharts.stockChart('grafico', {
chart: {
type: 'column',
renderTo: 'container'
},
title: {
text: 'Monto acumulado por ventas diarias'
},
subtitle: { text: '' },
// ✅ 关键修正:移除 categories,启用 datetime 轴
xAxis: {
type: 'datetime', // 显式声明(虽为默认,但推荐保留)
labels: {
formatter: function() {
return Highcharts.dateFormat('%b %e', this.value); // 如 "Jun 15"
}
}
},
yAxis: {
min: 0,
title: { text: 'Monto Acumulado (Colombiano)' }
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key:%Y-%m-%d}</span>
| Monto: | ' + '{point.y:,.0f} Colombiano |











