You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Highcharts中实现00:00时刻显示月日格式的时间

当前图表显示

实现时间的条件格式化方案

得用条件格式化逻辑,不能用固定的格式字符串,因为固定格式没法区分00:00/24:00和其他时间。下面是通用的实现思路,适配绝大多数支持自定义格式化函数的图表库(比如Highcharts、ECharts这类):

  • 写一个自定义格式化函数,先判断当前时间的小时和分钟是不是都是0(也就是00:00/24:00)
  • 如果是,就返回%b %e对应的格式(就是“Sep 7”这种样式)
  • 如果不是,就返回%H:%M的时分格式

拿Highcharts举例子,代码大概是这样:

xAxis: {
    type: 'datetime',
    labels: {
        formatter: function() {
            const date = new Date(this.value);
            const hours = date.getHours();
            const minutes = date.getMinutes();
            
            if (hours === 0 && minutes === 0) {
                // 00:00/24:00时显示日期
                return Highcharts.dateFormat('%b %e', this.value);
            } else {
                // 其他时间显示时分
                return Highcharts.dateFormat('%H:%M', this.value);
            }
        }
    }
}

要是用ECharts,代码逻辑差不多:

xAxis: {
    type: 'time',
    axisLabel: {
        formatter: function(value) {
            const date = new Date(value);
            const hours = date.getHours();
            const minutes = date.getMinutes();
            
            if (hours === 0 && minutes === 0) {
                return `${date.toLocaleString('en-US', { month: 'short' })} ${date.getDate()}`;
            } else {
                return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
            }
        }
    }
}

核心就是通过自定义函数判断时间点,根据情况返回不同格式——单一的格式化字符串根本做不到这种差异化显示。

内容的提问来源于stack exchange,提问作者jMoore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 02:35:22