这篇文章距离上次修改已过半年,其中的信息可能已经有所发展或是发生改变。

转换为语音并朗读全文 00:00 / 00:00

代码

如下,使用数组合并加正则替换

函数写法 (ES6)

function timeout(second) {
  const oneHour = 60 * 60
  const oneDay = oneHour * 24
  const oneYear = oneDay * 365
  return [
    parseInt(second / oneYear) + '年',
    parseInt(second % oneYear / oneDay) + '天',
    parseInt(second % oneDay / oneHour) + '小时',
    parseInt(second % oneHour / 60) + '分',
    parseInt(second % 60) + '秒'
  ]
    .join('')
    .replace(/\b(\d)\b/g, '0$1') // 自动补零
    .replace(/\b(\d+)\b/g, ' $1 ') // 数字两边加空格
    .replace(/(\s00\s([^\s]+))?/g, '') // 移除 00 时间
}

调用方法

timeout(second)

应用场景

普通示例

在线示例

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>时间如白驹过隙</title>
</head>

<body>
  <div id="timeout"></div>
  <script>
    // 转换时间
    function timeout (second) {
      const oneHour = 60 * 60
      const oneDay = oneHour * 24
      const oneYear = oneDay * 365
      return [
        parseInt(second / oneYear) + '年',
        parseInt(second % oneYear / oneDay) + '天',
        parseInt(second % oneDay / oneHour) + '小时',
        parseInt(second % oneHour / 60) + '分',
        parseInt(second % 60) + '秒'
      ]
        .join('')
        .replace(/\b(\d)\b/g, '0$1')
        .replace(/\b(\d+)\b/g, ' $1 ')
        .replace(/(\s00\s([^\s]+))?/g, '')
    }

    // 自执行函数
    (function lost () {
      const last = (new Date('2017-05-31T23:18:00')).getTime()
      const now = (new Date()).getTime()
      document.getElementById('timeout').innerText = timeout((now - last) / 1000)
      setTimeout(() => lost(), 1000)
    })()
  </script>
</body>

</html>

简便写法

在线示例

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>时间如白驹过隙</title>
</head>

<body>
  <div id="timeout"></div>
  <script>
    // 自执行函数
    (function timeout () {
      const oneHour = 60 * 60
      const oneDay = oneHour * 24
      const oneYear = oneDay * 365
      const last = (new Date('2017-05-31T23:18:00')).getTime()
      const now = (new Date()).getTime()
      const second = (now - last) / 1000
      document.getElementById('timeout').innerText = [
        parseInt(second / oneYear) + '年',
        parseInt(second % oneYear / oneDay) + '天',
        parseInt(second % oneDay / oneHour) + '小时',
        parseInt(second % oneHour / 60) + '分',
        parseInt(second % 60) + '秒'
      ]
        .join('')
        .replace(/\b(\d)\b/g, '0$1')
        .replace(/\b(\d+)\b/g, ' $1 ')
        .replace(/(\s00\s([^\s]+))?/g, '')
      setTimeout(() => timeout(), 1000)
    })()
  </script>
</body>

</html>
带符号 * 的表示必填项
  1. 背杰
    背杰

    感谢!

    回复
  2. 励志语录
    励志语录

    学习了,感谢

    回复