使用Javascript从时区名称获取时区偏移量 [英] Get timezone offset from timezone name using Javascript

查看:74
本文介绍了使用Javascript从时区名称获取时区偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了许多从偏移值给出时区名称的解决方案.但我有时区名称,我想要偏移值.我试过 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从时区名称获取时区偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆