【问题标题】:How to get only timeZoneName in Date Object in any language?如何以任何语言仅获取日期对象中的 timeZoneName?
【发布时间】:2020-12-04 21:55:06
【问题描述】:

我试图从 Date 对象中仅提取 timeZoneName。我用正则表达式用英语做,但是如何用法语等不同的语言做。我意识到正则表达式不是这个选项。如何仅获取 timeZoneName?

let d = new Date().toString();
    let finalD = (d.substring(d.search("GMT"), d.length));
    const [gmt, time] = finalD.split('(');
    const timezone = time.replace(/\)/g, "");
    console.log(gmt, timezone);

【问题讨论】:

  • 无论是什么语言,我都需要 timeZoneName ex:"Eastern Standard Time"。

标签: javascript date timezone


【解决方案1】:

在大多数现代 JavaScript 环境中,您可以使用 ECMAScript 国际化 API 来实现这一点。特别是DateTimeFormat 公开了您可以使用的功能。

const d1 = new Date(2020, 0, 1);
const d2 = new Date(2020, 6, 1);

const dtf1 = new Intl.DateTimeFormat('en', { timeZoneName: 'long'});
const dtf2 = new Intl.DateTimeFormat('fr', { timeZoneName: 'long'});

console.log(dtf1.formatToParts(d1).find(x => x.type ==='timeZoneName').value);
console.log(dtf1.formatToParts(d2).find(x => x.type ==='timeZoneName').value);
console.log(dtf2.formatToParts(d1).find(x => x.type ==='timeZoneName').value);
console.log(dtf2.formatToParts(d2).find(x => x.type ==='timeZoneName').value);

在上面的示例中,我展示了两种不同语言和两个不同日期的格式化程序。这突出表明该值将根据是标准时间还是夏令时有效而有所不同。

其他几点:

  • 如果您省略传递给formatToPartsDate 对象,它将使用当前日期和时间(与new Date() 相同)。

  • 如果您传递undefined 而不是语言代码,它将使用用户的默认语言。

  • DateTimeFormat 上调用其他方法或在Date 对象实例上调用toLocaleString 和类似函数时,您也可以使用timeZoneName 选项。我使用formatToParts 来轻松获取只是时区名称,而无需进行任何字符串操作。

【讨论】:

  • 我有同样的问题,但想知道是否有办法在没有 formatToParts 的情况下做到这一点,因为 IE11 不支持它。由于某种原因,仅使用 timeZoneName 作为 DateTimeFormat 的选项也会返回日期。
猜你喜欢
  • 2017-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-14
  • 1970-01-01
  • 1970-01-01
  • 2013-03-23
  • 1970-01-01
相关资源
最近更新 更多