1. 首页>>前端>>javascript

给网站添加一个运行时间

  这段代码首先定义了开始时间(2023年10月1日),并获取当前时间戳。然后,它计算出网站的运行时间(当前时间减去开始时间),并使用一系列的Math.floor函数和模运算来提取出网站运行的总年数、月数、天数、小时数、分钟数和秒数。最后,它将这些值组合成一个字符串,包括年和月、日和小时的格式,并将其显示在页面上的<p>元素中。

  通过调用calculateRuntime函数,我们可以在页面加载时计算出初始的网站运行时间。然后,使用setInterval函数每秒调用一次calculateRuntime函数,实现实时更新网站运行时间的效果。

  <!DOCTYPE html>
  <html>
  <head>
  <title>网站运行时间</title>
  </head>
  <body>
  <h1>网站运行时间</h1>
  <p id="runtime"></p>
  <script>
  // 定义开始时间(2023年10月1日)
  const startTime = new Date(2023, 9, 1); // 月份从0开始,所以需要减1
  const startTimestamp = startTime.getTime();
  function calculateRuntime() {
  // 获取当前时间戳(毫秒)
  const currentTimestamp = Date.now();
  // 计算网站运行时间(毫秒)
  const runtime = currentTimestamp - startTimestamp;
  // 计算网站运行时间(年、月、日和小时)
  const years = Math.floor(runtime / (1000 * 60 * 60 * 24 * 365.25)); // 考虑闰年
  const months = Math.floor((runtime % (1000 * 60 * 60 * 24 * 365.25)) / (1000 * 60 * 60 * 24 * 30)); // 一个月按30天计算
  const days = Math.floor((runtime % (1000 * 60 * 60 * 24 * 30)) / (1000 * 60 * 60 * 24));
  const hours = Math.floor((runtime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const minutes = Math.floor((runtime % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((runtime % (1000 * 60)) / 1000);
  const runtimeString = `${years}/年${months}/月${days}/日${hours}/时${minutes}/分${seconds}/秒`;
  document.getElementById('runtime').textContent = runtimeString;
  }
  calculateRuntime(); // 初始加载时计算运行时间
  // 使用setInterval函数每秒更新运行时间
  setInterval(calculateRuntime, 1000); // 每秒调用一次calculateRuntime函数以实现实时更新
  </script>
  </body>
  </html>


1.png

一些细节的东西,可以根据自己修改


转载联系作者并注明出处:https://www.focusonseo.cn/jcczs/157.html