情节.js为类型设置时区:“日期”

Plotly.js setting timezone for type:"date"

本文关键字:日期 时区 设置 js 类型 情节      更新时间:2023-09-26

我正在制作一个图表来显示一段时间内的状态。所有数据均采用 unix 格式。我使用 javascript (new Date(data)).toUTCString 在标题中显示数据。这与用于图表的数据相同,但图表提前 1 小时运行。图像

这是我的布局配置:

layout = {
    "showlegend": true,
    "title": new Date(min).toUTCString() + " to " + new Date(max).toUTCString(),
    "xaxis": {
        "autorange": true,
        "range": [
            min,
            max
        ],
        "title": "Time",
        "type": "date"    //if I change this to scatter, I get the unix values
    }
}
 Plotly.newPlot('graphMain', temp, layout); //temp contains the arrays

我目前居住在奥地利 (UTC+01:00)。有人对此有想法吗?

Plotly 目前不支持时区。

如果需要将

日期时间预先计算为本地时区或 UTC,则可能需要使用类似 moment.js 时区的内容。或者,如果您愿意,可以手动完成。

今天,我认为 Plotly.js 仍然不支持时区,或者至少我找不到它。这就是我解决它的方式,但是,如果你有更好的解决方案,我很高兴听到!

我想日期的原始格式是 yyyy-mm-ddTHH:MM:SSZ ,然后您使用 https://stackoverflow.com/a/74341794/11692632 中的函数更改格式,该函数获取 pc 的时区。

function fmt(date, format = 'YYYY-MM-DD hh:mm:ss') {
  const pad2 = (n) => n.toString().padStart(2, '0');
  //These functions get the date from the browser timezone, in my case 'Europe/Madrid'
  const map = {
    YYYY: date.getFullYear(),
    MM: pad2(date.getMonth() + 1),
    DD: pad2(date.getDate()),
    hh: pad2(date.getHours()),
    mm: pad2(date.getMinutes()),
    ss: pad2(date.getSeconds()),
  };
  return Object.entries(map).reduce((prev, entry) => prev.replace(...entry), format);
}
> date = '2022-12-15T10:00:00Z'
'2022-12-15T10:00:00Z'
> newDate = new Date(date)
2022-12-15T10:00:00.000Z
> fmt(new Date(date))
'2022-12-15 11:00:00'

注意,当然,如果您使用的是 unix 时间,它也可以工作

> date = 1671100918000
1671100918000
> newDate = new Date(date)
2022-12-15T10:41:58.000Z
> newDate.toLocaleString('se-SE', { timeZone: 'Europe/Madrid' })
'2022-12-15 11:41:58'

因此,如果我的日期数组是 dates ,要将日期转换为我的时区,您应该执行以下操作:

> const tz_dates=dates.map(date=>fmt(new Date(date)))