[英]Get current GMT offset from a timezone identifier
如何从时区标识符中获取当前的 GMT 偏移量? 理想情况下,它也将包含长格式名称。
例如:
"America/Los_Angeles" //output: GMT-0700 (Pacific Daylight Time)
如果它也可以与 ISO 字符串一起使用,那就太好了,例如:
2020-12-21T03:57:00Z //output: GMT-0800 (Pacific Standard Time)
您可以使用Intl.DateTimeFormat object 的timeZone和timeZoneName选项来获取更常见的时区的名称,但可能会缺少鲜为人知的时区。 还:
例如
// Get short offset, might show the actual offset but might be a short name let formatterA = new Intl.DateTimeFormat('en',{timeZone:'America/New_York', timeZoneName:'short'}); console.log( formatterA.format(new Date()) ); // 5/2/2020, EDT // Get short offset, might show the actual offset but might be a short name let formatterB = new Intl.DateTimeFormat('en',{timeZone:'America/New_York', timeZoneName:'long'}); console.log( formatterB.format(new Date()) ); // 5/2/2020, Eastern Daylight Time
获取偏移量的另一种策略是在时区中生成一个日期,并通过解析结果来获取与具有相同年、月、日等值的 UTC 日期的差异。 它仍然存在夏令时边界问题。 Intl.DateTimeFormat.prototype.formatToParts方法有助于解决这个问题。
但是,我建议您使用像Luxon这样的库,因为弄乱这些东西可能会让您头疼,尤其是在夏令时更改方面。
var DateTime = luxon.DateTime; let d = DateTime.fromISO("2017-05-15T09:10:23", { zone: "Europe/Paris" }); console.log(d.toFormat('ZZ')); // +02:00 console.log(d.toFormat('ZZZZZ')); // Central European Summer Time let e = DateTime.fromISO("2017-05-15T09:10:23", { zone: "Pacific/Kiritimati" }); console.log(e.toFormat('ZZ')); // +14:00 console.log(e.toFormat('ZZZZZ')); // Line Islands Time
<script src="https://cdn.jsdelivr.net/npm/luxon@1.23.0/build/global/luxon.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.