如何修改现有JavaScript代码以展示Asia/Dhaka时区的实时时间
展示Asia/Dhaka时区实时时间的代码修改方案
原代码通过getHours()/getMinutes()/getSeconds()读取的是运行设备的本地系统时间,要切换为指定时区的实时时间读数,无需引入第三方时区工具库,借助浏览器原生Intl.DateTimeFormatAPI即可实现,原有代码的补零、定时刷新逻辑可完整保留。
改动要点
- 移除Date对象直接读取本地时间分量的逻辑,通过绑定
Asia/Dhaka时区的格式化器提取对应时区的时、分、秒数值 - 统一对时、分、秒做小于10补零的处理,保证输出格式为标准的
HH:mm:ss - 关闭格式化器的12小时制输出,避免出现AM/PM标识
- 提前初始化格式化器实例,避免每次轮询重复创建对象造成的性能损耗
- 原有的500ms间隔轮询逻辑保持不变,足够支撑实时展示的流畅度要求
修改后的完整代码
function checkTime(i) { if (i < 10) { i = "0" + i; } return i; } // 初始化绑定Dhaka时区的格式化器 const dhakaTimeFormatter = new Intl.DateTimeFormat('en-US', { timeZone: 'Asia/Dhaka', hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: false }); function startTime() { const today = new Date(); // 提取目标时区的时间分量 const timeParts = dhakaTimeFormatter.formatToParts(today); const h = Number(timeParts.find(part => part.type === 'hour').value); const m = Number(timeParts.find(part => part.type === 'minute').value); const s = Number(timeParts.find(part => part.type === 'second').value); // 统一补零处理 const formattedH = checkTime(h); const formattedM = checkTime(m); const formattedS = checkTime(s); document.getElementById('time').innerHTML = formattedH + ":" + formattedM + ":" + formattedS; t = setTimeout(function() { startTime() }, 500); } startTime();
该实现完全基于浏览器原生API运行,无额外依赖,可直接替换原代码在所有现代浏览器环境下使用。
内容的提问来源于stack exchange,提问作者Ahmed Mohammed
相关产品推荐
相关产品推荐

