一、常用

  1. var d = new Date()
  2. /* 年,月,日 */
  3. var year = d.getFullYear()
  4. var month = d.getMonth()+1 // 月份是从0开始的,要加1
  5. var date = d.getDate()
  6. /* 时,分,秒 */
  7. var hour = d.getHours();
  8. var minute = d.getMinutes();
  9. var second = d.getSeconds();
  10. var mills = d.getTime(); //毫秒 1s = 1000毫秒
  11. console.log(d);
  12. console.log(year);
  13. console.log(month);
  14. console.log(date);
  15. console.log(hour);
  16. console.log(minute);
  17. console.log(second);

例1:时间戳

<p id="app"></p>
    <script>
        function handleTime(value) {
            if (value < 10) {
                return "0" + value
            }
            return "" + value
        }

        function showTime() {
            var app = document.getElementById("app")

            var endTime = "2020-12-01 16:50:00";
            // 转换成毫秒
            endTime = new Date(endTime).getTime(endTime)
            var nowTime = new Date().getTime()

            // 获取时间差
            var gapTime = endTime - nowTime;
            console.log(gapTime)

          // 获取小时
            var hourse = handleTime(Math.floor(gapTime / 3600000));
            console.log(hourse)

          // 获取分钟
            var minu = handleTime(Math.floor(gapTime / 60000 % 60))
            console.log(minu)

          // 获取秒
            var seconds = handleTime(Math.floor(gapTime / 1000 % 60))
            console.log(seconds)
            var sum = hourse + ":" + minu + ":" + seconds;
            console.log(sum)

          // 将时间传入p标签内
            app.innerHTML = sum;

          //间歇调用 递归
            setTimeout(function () {
                showTime()
            }, 1000)
        }
        showTime();
    </script>

例2:时间图

<div id="app">
        <img src="./images/0.png" alt="">
        <img src="./images/0.png" alt="">
        <span>:</span>
        <img src="./images/0.png" alt="">
        <img src="./images/9.png" alt="">
        <span>:</span>
        <img src="./images/8.png" alt="">
        <img src="./images/7.png" alt="">
    </div>
    <script>
        function handleTime(value) {
            if (value < 10) {
                return "0" + value
            }
            return "" + value
        }

        function showTime() {
            var app = document.getElementById("app")
            var imgs=document.getElementsByTagName("img")
            var d = new Date();
            var hour = d.getHours();  // 小时
            var minutes =d.getMinutes();  // 分
            var second =d.getSeconds();  // 秒
            var sum =handleTime(hour) +handleTime(minutes)+handleTime(second)
            console.log(sum)

            for(var i=0;i<imgs.length;i++){
                imgs[i].src="./images/"+sum[i]+".png"
            }

            //间歇调用 递归
            setTimeout(function () {
                showTime()
            }, 1000)
        }
        showTime();
        console.log(imgs.length)
    </script>