简体   繁体   English

如何计算给定时区的时区偏移量

[英]how to calculate timezone offset from given timezone

I have a case where I am trying to calculate timezoneOffset from selected timezone.我有一个案例,我试图从选定的时区计算 timezoneOffset。

The sample I am saving the time in the database as UTC format, Now I am calculating the timezone as per user's location/timezone and setting the timezone offset.我将数据库中的时间保存为 UTC 格式的示例,现在我正在根据用户的位置/时区计算时区并设置时区偏移量。

How I can create mapping that -330 offset if from which timezone, I want to calculate it for all the timezone.如果从哪个时区开始,我如何创建-330偏移量的映射,我想为所有时区计算它。 Example [{ timezone: 'Australia/Sydney', offset: '660' }] and so on..示例 [{ timezone: 'Australia/Sydney', offset: '660' }] 等等..

such that I can search for -330 offset is for which timeozne.这样我就可以搜索 -330 偏移量是哪个 timeozne。

Suppose -330 offset if for which timezone?如果是哪个时区,假设-330 偏移量? Where I can create mapping with offset and timezone.我可以在哪里创建带有偏移量和时区的映射。

Example User a is from Australia/Sydney then how can I check timezone offset from UTC?示例用户 a 来自Australia/Sydney ,那么如何检查与 UTC 的时区偏移量?

Just a note that I have multiple timezones to support overall more than 30 time zones.请注意,我有多个时区来支持总共 30 多个时区。

And I want something very accurate calculation.我想要一些非常准确的计算。

I know momentjs using it I can do, but suddenly don't know-how.我知道 momentjs 使用它我可以做到,但突然不知道怎么做。

with momentjs I get UTCoffser of Australia/Sydney //660与momentjs我得到Australia/Sydney的UTCoffser //660

Can anyone help me derive the accurate date here?谁能帮我在这里推算出准确的日期?

If you have the IANA name for your timezone, you can pass it into Intl.DateTimeFormat and filter out and calculate the offset:如果您的时区有IANA名称,则可以将其传递到Intl.DateTimeFormat并过滤掉并计算偏移量:

 const getUTCOffset = timezone => Intl.DateTimeFormat([], {timeZone: timezone, timeZoneName: 'shortOffset'}).formatToParts().find(o => o.type === 'timeZoneName').value.match(/\-?\d+/)[0]*60; console.log(getUTCOffset('Australia/Sydney'))


If you're running this code in the user's browser and want to use the user's timezone, then it's even simpler:如果您在用户的浏览器中运行此代码并希望使用用户的时区,那么它就更简单了:

new Date().getTimezoneOffset()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM