在 JavaScript 中获取特定的时区时间

问题描述

我在印度工作,想了解欧洲/伦敦的时间详情。 在下面的代码中,我为初始化 DateTimeFormat 提供了欧洲/伦敦时区。 初始化后,我无法以小时(24 小时格式)、分钟和秒的形式单独获取时间值。

如果我尝试使用resolvedOptions() 获取小时值,那么它会产生“2 位数字”。

我想以 24 小时格式打印小时数,例如“22”:12 :02

有没有办法修改代码

或者有没有其他方法可以将时间值单独提取到小时、分钟和秒中。

function getEuropeTime() {
  let options = {
      timeZone: 'Europe/London',hour: 'numeric',minute: 'numeric',second: 'numeric',hour12: false,},formatter = new Intl.DateTimeFormat([],options);
  var date = formatter.format(new Date())
  var usedOptions = formatter.resolvedOptions();
  console.log(usedOptions.hour);
  console.log(date);
}

getEuropeTime();

解决方法

let options = {
    timeZone: 'Europe/London',hour: 'numeric',minute: 'numeric',second: 'numeric',hour12: false,},formatter = new Intl.DateTimeFormat([],options);
  var date=formatter.format(new Date())
  var parts = formatter.formatToParts();
  console.log(parts)
  console.log(parts.find(c=>c.type=='hour').value);
  console.log(date)

在这里您还可以检查其他部分,例如分钟和秒。 resolveOptions 只返回用于格式化的选项值。有关更多详细信息,请查看此处intl.DateTimeFormat

,

您将浏览器默认语言作为默认语言传递,所以您真的不知道时间会是什么格式。

在某些情况下,使用浏览器默认值可能没问题,但这几乎总是不是一个好主意。页面以特定语言呈现,因此日期、数字等应遵循该语言的约定,而不是浏览器设置的任何随机语言(由于某些深不可测的原因,几乎总是 en-US)。

此外,语言设置通常会覆盖选项,尤其是 hour12 选项。最好(即最可靠和最稳健)的方法是使用 getHoursgetMinutesgetSeconds 方法根据需要手动格式化时间。

如果您真的想使用 Intl.DateTimeFormat 构造函数,请选择默认使用您想要的格式的语言(CLDR project 可以提供帮助,或者只是测试各种语言标签)。对其进行彻底测试,以确保您关注的所有实现都是一致的。

function getEuropeTime(){
  return new Date().toLocaleString('en',{
    hour: '2-digit',minute: '2-digit',second: '2-digit',timeZone: 'Europe/London'
  });
}

console.log(getEuropeTime());

使用 formatToParts 和手动格式化:

function getEuropeTime(d = new Date()) {
  let {hour,minute,second} = new Intl.DateTimeFormat('en',timeZone: 'Europe/London'
  }).formatToParts(d).reduce((acc,part) => {
    acc[part.type] = part.value;
    return acc;
  },Object.create(null));
  return `${hour}:${minute}:${second}`;
}

console.log(getEuropeTime(new Date(Date.UTC(2020,12,15))));

请注意,伦敦实行夏令时,但欧洲部分地区不实行。此外,欧盟正在考虑完全取消夏令时,因此您可能需要重命名该职能或使用不同的 IANA 代表位置。