javascript - 在 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
推荐阅读
- linux - 默认根用户文件权限
- c++ - 为什么编译成功?
- javascript - 不使用ipc直接把主要的东西放在preload.js中好吗?
- flutter - 颤振错误->必须初始化不可为空的“项目”
- integration-testing - 如何使用 WebApplicationFactory 对 .NET 6 Web Api 项目进行集成测试?
- reactjs - 渲染没有返回任何内容。这通常意味着缺少返回语句
- composer-php - Laminas-Cache 2.13 PHP8 升级
- c++ - 如何从文件和用户输入 C++ 中读取输入
- javascript - 加载模块脚本失败..“text/html”的 MIME 类型 - Javascript、Node.js 和 Parcel
- python - 引发 python 异常然后继续