问题描述
我找到了许多从偏移值给出时区名称的解决方案.但我有时区名称,我想要偏移值.我试过 setTimezone('Asia/Kolkata'),但我认为它们不像 setTimezone 那样的方法.
I found many solution that gives Timezone name from offset value. But I have Timezone name and I want offset value for that. I tried setTimezone('Asia/Kolkata'), but I think their is no method like setTimezone.
示例:
Asia/Kolkata should give me -330 ( offset )
推荐答案
我遇到了同样的问题,这就是我想出的解决方案,如果你能得到 IANA tz 数据库名称 就像你提到的那个:
I came across this same issue, and this is the solution I came up with, if you can get an IANA tz database name like the one you mentioned:
var myTimezoneName = "Asia/Colombo";
// Generating the formatted text
var options = {timeZone: myTimezoneName, timeZoneName: "short"};
var dateText = Intl.DateTimeFormat([], options).format(new Date);
// Scraping the numbers we want from the text
var timezoneString = dateText.split(" ")[1].slice(3);
// Getting the offset
var timezoneOffset = parseInt(timezoneString.split(':')[0])*60;
// Checking for a minutes offset and adding if appropriate
if (timezoneString.includes(":")) {
var timezoneOffset = timezoneOffset + parseInt(timezoneString.split(':')[1]);
}
这不是一个非常好的解决方案,但它无需导入任何内容即可完成工作.它依赖于 Intl.DateTimeFormat 的输出格式是否一致,这应该是一致的,但这是一个潜在的警告.
It's not a very nice solution, but it does the job without importing anything. It relies on the output format of the Intl.DateTimeFormat being consistent, which it should be, but that's a potential caveat.
这篇关于使用Javascript从时区名称获取时区偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!