我有一个基于我的 MVC 控制器提供的 .NET 方法System.TimeZoneInfo.GetSystemTimeZones
时区的下拉列表。我想做的是捕获用户的时区(客户端(并将下拉列表默认为他们的时区。
在Chrome和Firefox上,当我在控制台上输入new Date()
时,我可以得到一个字符串,例如Fri Jan 24 2020 08:50:02 GMT-0500 (Eastern Standard Time)
除了在括号之间解析之外,有没有办法获取时区字符串东部标准时间?
我用它来获取 gmt 文本。它被淘汰了,但可能会起作用
new Date().toString().split('(')[1].split(')')[0]
这个怎么样?
Intl.DateTimeFormat().resolvedOptions().timeZone
我可以建议使用Moment
,这是一个第三方库,用于处理从时间到日期的所有内容。我真的非常推荐这个。
官方时刻文档:https://momentjs.com/
在您的问题中,您可以使用以下时刻轻松获得时区:
var jun = moment("2014-06-01T12:00:00Z");
var dec = moment("2014-12-01T12:00:00Z");
jun.tz('America/Los_Angeles').format('z'); // PDT
dec.tz('America/Los_Angeles').format('z'); // PST
jun.tz('America/New_York').format('z'); // EDT
dec.tz('America/New_York').format('z'); // EST
// This gets you your current timezone
moment().tz(Intl.DateTimeFormat().resolvedOptions().timeZone).format('z')
// Other examples
jun.tz('Asia/Tokyo').format('ha z'); // 9pm JST
dec.tz('Asia/Tokyo').format('ha z'); // 9pm JST
jun.tz('Australia/Sydney').format('ha z'); // 10pm EST
dec.tz('Australia/Sydney').format('ha z'); // 11pm EST
您可以从日期getTimezoneOffset
函数获取当前时区偏移量(以分钟为单位(。然后,您可以将该数字除以60
以获得以小时为单位的实际偏移量。请注意,偏移量是"GMT+0100"字符串的加法反转数字。
const offset = new Date().getTimezoneOffset() / 60;
console.log('Offset: ', offset);
console.log('UTC: ', new Date().toUTCString());
console.log('GMT: ', new Date().toString());
请参阅文档:
getTimezoneOffset(( 方法返回从当前区域设置(主机系统设置(到 UTC 的时区差异(以分钟为单位(。