Article cover

页面显示时间练习

需求:将当前时间以:YYYY-MM-DD HH:mm 形式显示在页面 2008-08-08 08:08

分析

  1. 调用日期对象方法进行转换
  2. 记得数字要补0
  3. 字符串拼接后,通过 innerText 给 标签

代码实现

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    div {
      width: 500px;
      height: 50px;
      border: 3px solid pink;
      border-radius: 10px;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
      text-align: center;
      line-height: 50px;
      position: absolute;
      font-size: 30px;
      color: skyblue;
    }
  </style>
</head>

<body>
  <div></div>
  <script>
    const div = document.querySelector('div')
    function getMyDate() {
      const date = new Date()
      let h = date.getHours()
      let m = date.getMinutes()
      let s = date.getSeconds()
      h = h < 10 ? '0' + h : h
      m = m < 10 ? '0' + m : m
      s = s < 10 ? '0' + s : s
      return `今天是: ${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${h}:${m}:${s}`
    }
    div.innerHTML = getMyDate()
    setInterval(function () {
      div.innerHTML = getMyDate()
    }, 1000)
  </script>
</body>

</html>

效果示例

屏幕截图 2023-11-20 163943.png

Comments

Contents

404NotFound

Keyboard shortcuts

Ctrl/⌘+F
Open site search; press again while open for browser Find. Editing areas keep their original behavior.
Shift+D
Toggle appearance, except while editing text.
Esc
Close a theme menu or dismissible overlay.
↑ ↓
Select the previous or next quick action.
← →
Move between the toolbar icons.
Home End
Select the first or last quick action.
Enter Space
Run the selected action.
Tab
Leave the quick menu and continue through the page.

Hold Shift while right-clicking to keep the native menu.

Copy page link