timeDisplay.js 1.2 KB

1234567891011121314151617181920212223242526272829303132
  1. /**
  2. * 公用时间显示功能
  3. * 格式:yyyy年MM月dd日星期X HH:mm:ss
  4. */
  5. export function initTimeDisplay(elementId) {
  6. // 时间更新函数
  7. function updateNativeTime() {
  8. const now = new Date();
  9. const year = now.getFullYear();
  10. const month = String(now.getMonth() + 1).padStart(2, '0');
  11. const day = String(now.getDate()).padStart(2, '0');
  12. const hours = String(now.getHours()).padStart(2, '0');
  13. const minutes = String(now.getMinutes()).padStart(2, '0');
  14. const seconds = String(now.getSeconds()).padStart(2, '0');
  15. const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  16. const weekday = weekdays[now.getDay()];
  17. // 移除月份和日期的前导零
  18. const monthNum = now.getMonth() + 1;
  19. const dayNum = now.getDate();
  20. const timeString = `${year}年${monthNum}月${dayNum}日 ${weekday} ${hours}:${minutes}:${seconds}`;
  21. const timeElement = document.getElementById(elementId);
  22. if (timeElement) {
  23. timeElement.textContent = timeString;
  24. }
  25. }
  26. // 立即执行一次
  27. updateNativeTime();
  28. // 每秒更新
  29. setInterval(updateNativeTime, 1000);
  30. }