将时区设置为 "Europe/London" 时,IE 11 抛出“'timeZone' 超出有效范围”

IE 11 throwing "'timeZone' is outside of valid range" when setting timezone to "Europe/London"

我有一些 js 可以让本地时间显示在英国时区。

var d = new Date(); // local system time (whatever timezone that is)
var dUK = new Date(d.toLocaleString('en-GB', { timeZone: 'Europe/London' })); // UK timezone (covers BST too)

在所有浏览器中工作正常,除了 IE 11(唉...)会抛出以下错误:

Option value 'EUROPE/LONDON' for 'timeZone' is outside of valid range. Expected: ['UTC']

有人有什么建议吗?请参阅 http://jsbin.com/dawaqocuvi/1/edit?html,js,console,output 以获取支持 IE 的示例 fiddle。

IE11,在使用时区选项时对日期格式的支持有限,基本上唯一有效的选项是UTC。不是很有用。

我能想到的两个选项。

  1. 使用 momentjs,这是一个不错的日期时间库,但可能有点矫枉过正
  2. 使用 pollyfill

下面是一个片段,polyfill 是语言环境时区,并创建了一个简单的世界时钟,有几个时区..

如果您的 运行 是现代浏览器,您应该能够在开始时删除脚本标签,它将继续工作。

Update: Got this working now in IE11, case is important when doing the locale with the polyfill. eg. Europe/Amsterdam is fine, but europe/amsterdam is not, with Chrome it didn't seem to matter.

//var d = new Date(); var dUK = d.toLocaleString('en-GB', { timeZone: 'America/Chicago' }); console.log(dUK);

function updateTimes() {
  var dt = new Date();
  var els = document.querySelectorAll("[data-tz]");
  for (var l = 0; l < els.length; l ++) {
    var d = els[l];
    d.innerText = dt.toLocaleString('en-GB', {timeZone: d.dataset.tz});
  }
}

updateTimes();
setInterval(updateTimes, 1000);
<script src="https://unpkg.com/date-time-format-timezone@latest/build/browserified/date-time-format-timezone-complete-min.js"></script>

<p>Simple world time clocks</p>

<div><span data-tz="Europe/London"></span>
  - London
</div>
<div>
  <span data-tz="Europe/Amsterdam"></span>
  - Amsterdam
</div>
<div>
  <span data-tz="America/Chicago"></span>
  - Chicago
</div>

是的,如上所述,IE 11 支持大部分 Intl API 但不支持使用特定时区:http://kangax.github.io/compat-table/esintl/#test-DateTimeFormat_accepts_IANA_timezone_names

这是一个示例,说明如何使用 webpack 的 require.ensure:

仅填充 Intl.DateTimeFormat 函数的时区支持
const fillIntlDateTimeFormatTimezone = () => new Promise((resolve) => {
    try {
        new Intl.DateTimeFormat('en', {
            timeZone: 'America/Los_Angeles',
            timeZoneName: 'long'
        }).format();
        return resolve();
    } catch (error) {
        require.ensure(['date-time-format-timezone'], (require) => {
            require('date-time-format-timezone');
            return resolve();
        }, 'DateTimeFormatTimezone');
    }
});

这应该只为不支持指定时区的浏览器加载 polyfill 属性 此时应该只是 IE 11。