How do I include a timezone in my d3 time formatted data?

我是研究僧i 提交于 2021-02-13 17:26:49

问题


I"m using d3 v4. My x-axis data consists of time in milliseconds (since 1970). I would like to display this as eastern standard time, for example

08/09/17 5:20 PM EDT

so I tried

focus.select("text").text(d.value).append("tspan")
      .attr("x", 10).attr("dy", "1.5em").text(d3.timeFormat("%m/%d/%Y %H:%M %p %Z+5")(d.index_date));

but unfortunately it is instead displaying as

08/09/17 5:20 PM -0500 +%

What's the proper way to format the date/time as EDT (US Eastern standard time)?


回答1:


D3 v4 time format has support for custom locales, but I don't see anything for time zones (so you can show the date-time in Russian, but only with the browser's local time zone), which is understandable, as it requires having the TZ data locally.

The only way I see is to bring another library.
Edit: no wait, Date.toLocaleString supports timeZone parameter (but it seems browser support is limited, e.g. Android does not support this (well, Chrome does, Firefox does not, and maybe WebViews won't)):

new Date(1502769000000).toLocaleString('en-US', { timeZone: 'America/New_York' })
// 8/14/2017, 11:50:00 PM"

(so you'd just need to add the "EDT" suffix yourself)

Alternatively, with moment-timezone (which itself requires moment):

var t = 1502769000000;
var f = 'M/D/Y h:mma z';
moment(t).tz('America/New_York').format(f);
// 8/14/2017 11:50pm EDT
moment(t).tz('Europe/Paris').format(f);
// 8/15/2017 5:50am CEST

Since you always need the same TZ, you might be interested to note that it's also technically possible to build a lighter version yourself with only the subset of TZ data you require.




回答2:


The toString() method on a regular javascript Date object includes the time zone abbreviation but the d3-time-format library doesn't seem to include a way to get it.

var date = new Date(123456789);
console.log(date.toString()); //"Fri Jan 02 1970 05:17:36 GMT-0500 (EST)"

var d3Format = d3.timeFormat("%c %Z");
console.log(d3Format(date)); //"1/2/1970, 5:17:36 AM -0500"

So you'll have to add in the time zone abbreviation manually with your own function.

var jenny = new Date(8675309);
var d3Format = d3.timeFormat("%c"); //%c is shorthand for %x %X (date and time)

// Add "EST" to the end of every string
var addEST = function(date) {
    return d3Format(date) + " EST";
}

console.log(addEST(jenny)); //"12/31/1969, 9:24:35 PM EST"


来源:https://stackoverflow.com/questions/45622916/how-do-i-include-a-timezone-in-my-d3-time-formatted-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!