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

TradingView轻量图表十字线工具提示时间显示异常问题求助

TradingView轻量图表十字线工具提示时间显示异常问题求助

大家好,我最近在做一个基于TradingView轻量图表的算法交易平台,遇到了个时间显示的小问题——图表X轴的时间已经正确显示为印度标准时间(IST)了,但十字线工具提示里的时间却总是跳出UTC格式,折腾了好几种写法,想跟大家分享下我的尝试,也看看有没有更优的方案。

尝试方案1:手动计算IST偏移量

我首先想到的是直接给UTC时间加上5.5小时的毫秒偏移,然后手动拼接日期时间字符串:

chart.subscribeCrosshairMove(param => {
  const div = document.getElementById('crosshairTimeDisplay');
  if (!param.time) {
    div.textContent = '';
    return;
  }
  const utcDate = new Date(param.time * 1000);
  const istTime = new Date(utcDate.getTime() + (5.5 * 3600 * 1000));
  const day = String(istTime.getDate()).padStart(2, '0');
  const month = istTime.toLocaleString('en-IN', { month: 'short' });
  const year = istTime.getFullYear();
  const hours = String(istTime.getHours()).padStart(2, '0');
  const minutes = String(istTime.getMinutes()).padStart(2, '0');
  const seconds = String(istTime.getSeconds()).padStart(2, '0');
  div.textContent = `${day}-${month}-${year} ${hours}:${minutes}:${seconds}`;
});

这种写法能得到正确的IST时间,但手动维护时区偏移量总觉得不够灵活,万一以后时区规则有变化(虽然印度目前没有夏令时),就得手动改代码。

尝试方案2:用toLocaleString直接指定时区

后来想到浏览器的国际化API可以直接处理时区,就改成了直接指定Asia/Kolkata时区的写法:

chart.subscribeCrosshairMove(param => {
  const div = document.getElementById('crosshairTimeDisplay');
  if (!param.time) {
    div.textContent = '';
    return;
  }
  const date = new Date(param.time * 1000);
  const options = {
    timeZone: 'Asia/Kolkata',
    year: 'numeric',
    month: 'short',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  };
  const istString = date.toLocaleString('en-IN', options);
  div.textContent = istString;
});

这种写法不用自己算偏移,浏览器会自动处理时区规则,代码也简洁了不少。

尝试方案3:用Intl.DateTimeFormat构造函数

还有一种更明确使用国际化API的写法,单独实例化日期格式化对象:

chart.subscribeCrosshairMove(param => {
  const div = document.getElementById('crosshairTimeDisplay');
  if (!param.time) {
    div.textContent = '';
    return;
  }
  const date = new Date(param.time * 1000);
  const formatter = new Intl.DateTimeFormat('en-IN', {
    timeZone: 'Asia/Kolkata',
    year: 'numeric',
    month: 'short',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
  div.textContent = formatter.format(date);
});

和第二种思路本质一样,但把格式化配置单独抽出来,要是需要在多个地方复用格式,这种写法更方便维护。

目前这三种写法都解决了我的问题,十字线工具提示终于能正确显示IST时间了。对比下来,后两种用国际化API的方式更健壮,不用自己操心时区细节。如果大家有更简洁或者更严谨的写法,欢迎一起交流~

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 09:43:02