将时区设置为“欧洲/伦敦”时,IE 11 抛出“'timeZone' 超出有效范围”

Sea*_*n T 8 javascript internet-explorer datetime localization internet-explorer-11

我有一些 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)
Run Code Online (Sandbox Code Playgroud)

在除 IE 11(sigh...) 之外的所有浏览器中都可以正常工作,它会引发以下错误:

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

有人有什么建议吗?有关支持 IE 的示例小提琴,请参见http://jsbin.com/dawaqocuvi/1/edit?html,js,console,output

Kei*_*ith 9

IE11, has limited support of date formatting when using the timezone option, basically the only valid option is UTC. Not very useful.

Two options that I can think off.

  1. Use momentjs, this is a nice datetime lib, but might be overkill
  2. Use a pollyfill

Below is a snippet, that polyfill's the locale timezone, and creates a simple world time clock, with a few zones..

If your running a modern browser, you should be able to remove the script tag at the start and it will continue to work.

更新:现在在 IE11 中可以正常工作,使用 polyfill 进行区域设置时大小写很重要。例如。Europe/Amsterdam很好,但europe/amsterdam不是,Chrome 似乎无关紧要。

//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);
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


Sun*_*yle 5

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

以下是如何使用 webpack 的仅填充 Intl.DateTimeFormat 函数的 timeZone 支持的示例require.ensure

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');
    }
});
Run Code Online (Sandbox Code Playgroud)

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

  • require.ensure() 特定于 webpack,并被 import() 取代。 (2认同)
  • 导入整个“date-time-format-timezone”时要小心,因为如果我没记错的话,它比整个“momentjs”库大 (2认同)