首页 > 解决方案 > 在 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();

标签: javascriptdatetimezonetimezone-offset

解决方案


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


推荐阅读