如何用JavaScript在页面每秒展示当前时区、日期和时间?
实现网页实时显示指定格式的时区、日期和时间
下面是直接可用的代码,能在网页上每秒更新并展示符合要求格式的当前时区、日期和时间:
<!DOCTYPE html> <html> <head> <title>实时时间显示</title> </head> <body> <div id="currentTime"></div> <script> const timeElement = document.getElementById('currentTime'); function updateTime() { const now = new Date(); // 生成(GMT±HH:MM)格式的时区字符串 const timeZoneOffset = now.getTimezoneOffset(); const hoursOffset = Math.abs(Math.floor(timeZoneOffset / 60)); const minutesOffset = Math.abs(timeZoneOffset % 60); const sign = timeZoneOffset > 0 ? '-' : '+'; const timeZoneStr = `(GMT${sign}${hoursOffset.toString().padStart(2, '0')}:${minutesOffset.toString().padStart(2, '0')})`; // 生成MM/DD/YYYY格式的日期字符串 const month = now.getMonth() + 1; const date = now.getDate(); const year = now.getFullYear(); const dateStr = `${month}/${date}/${year}`; // 生成12小时制带AM/PM的时间字符串 let hours = now.getHours(); const period = hours >= 12 ? 'PM' : 'AM'; hours = hours % 12 || 12; const minutes = now.getMinutes().toString().padStart(2, '0'); const seconds = now.getSeconds().toString().padStart(2, '0'); const timeStr = `${hours}:${minutes}:${seconds} ${period}`; // 更新页面显示 timeElement.textContent = `${timeZoneStr} ${dateStr} ${timeStr}`; } // 初始化显示+每秒更新 updateTime(); setInterval(updateTime, 1000); </script> </body> </html>
关键逻辑说明
- 时区计算:通过
getTimezoneOffset()获取当前时区与UTC的分钟差,转换为小时和分钟后拼接成指定的GMT格式。 - 日期格式化:直接提取月份(注意加1,因为JS月份从0开始)、日期、年份,按要求格式拼接。
- 时间格式化:将24小时制转为12小时制,自动判断AM/PM,不足两位的分、秒用补零处理。
- 实时更新:先执行一次初始化显示,再用
setInterval每秒触发一次更新函数。
内容的提问来源于stack exchange,提问作者WillTechX20
相关产品推荐
相关产品推荐

