1、时间对象

1.1【作用】:Date 对象用于处理日期和时间。

1.2【创建时间对象】: new Date()获取系统当前时间

  1. var myDate=new Date(); //Tue Dec 24 2019 20:44:00 GMT+0800 (中国标准时间);
  2. typeof myDate;====>"object" // 获取到是一个对象,并不是字符串

1.3 时间对象相关属性和方法

  • getFullYear();获取年
  • getMonth();获取月 0到11 代表1月到12月
  • getDate();获取日期
  • getDay();星期几 (0—-6)代表周日到到周六
  • getHours();时
  • getMinutes();分
  • getSeconds();秒
  • getMilliseconds();毫秒
  • getTime();获取当前日期到1970年1月1号 00:00:00 之间的毫秒差
  • toLocaleString();// 获取到的是年月日,时分秒”2019/12/25 上午10:15:50”
  • toLocaleDateString();// 获取到是字符串的年月日,例如:”2019/12/25”
  • toLocaleTimeString();/ 获取到的是字符串的时分秒上午10:18:28

    2、案例:钟表

    ```javascript <!DOCTYPE html>

  1. 0操作:
  2. ```javascript
  3. <!DOCTYPE html>
  4. <html lang="en">
  5. <head>
  6. <meta charset="UTF-8">
  7. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  8. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  9. <title>Document</title>
  10. <style>
  11. #clock{
  12. height:50px;
  13. line-height: 50px;
  14. text-align: center;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div class="clock" id="clock">
  20. </div>
  21. <script>
  22. var clock = document.getElementById("clock");
  23. function getTime() {
  24. var time = new Date();
  25. var year = time.getFullYear();
  26. var month = time.getMonth() + 1;
  27. var date = time.getDate();
  28. var day = time.getDay();
  29. var hour = time.getHours();
  30. var minutes = time.getMinutes();
  31. var seconds = time.getSeconds();
  32. var week = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  33. var res = year + "年" + addZero(month) + "月" + addZero(date) + "日" + week[day] + " " + addZero(hour) + ":" + addZero(minutes) + ":" + addZero(seconds);
  34. return res;
  35. }
  36. function addZero(num) {
  37. return num < 10 ? "0" + num : num;
  38. }
  39. var res = getTime();
  40. clock.innerText = res;
  41. setInterval(function () {
  42. var res = getTime();
  43. clock.innerText = res;
  44. }, 1000)
  45. </script>
  46. </body>
  47. </html>

3、定时器:

3.1、setTimeOut

 一定的时间后,去执行某些事情,是单次调用
setTimeout(function(){
    alert("wasai!you are beautiful");
},1000)

3.2、setInterval

间隔多少时间后,去执行某些事情,是多次调用

setInterval(function(){
    console.log("我真美!")
},1000)

3.3、定时器的参数说明

// 定时器可以传递多个参数:
// 1、执行的函数 
// 2、时间 
// 3、后面的参数就是执行函数在执行的时候传递的实参
setTimeout(function(num,s,m){
  console.log(num,s,m);
},1000,2,3,6);

3.4、定时器是有返回值的,返回值代表定时器处于当前页面中的第几个

var time1=setTimeout(function(){
    console.log("wasai!you are beautiful");
},1000)


var time2=setInterval(function(){
    console.log("我真美!")
},1000)

var time3=setTimeout(function(){
    console.log("aa");
},1000)

console.log(time1)=====>1
console.log(time1)=====>2
console.log(time1)=====>3

3.5、定时器是异步任务,只要当咱们同步代码执行完毕之后,才能执行。

setTimeout(function(){
    console.log("定时器");
},1000)
console.log("haha")

4、清除定时器的方法

  • clearTimeout
  • clearInterval ```javascript

var time1=setTimeout(function(){ console.log(‘1’) },1000)

clearTimeout(time1);

var time2=setInterval(function(){ console.log(“in”) },1000);

clearInterval(time2)

<a name="NHXgI"></a>
## 5、练习
做一个抽奖程序,页面中有一个区域显示中奖人员的编号,在JS中写一段代码,要求每隔1秒中随机创建一个四位的数字(每一位数字的取值范围0-9),当10秒结束后,结束定时器,最后显示的四位数字即是中奖的号码
```javascript
<!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>
    <style>
    #prize{
        width:200px;
        height:50px;
        border:1px solid green;
    }
    </style>
</head>
<body>
    <div class="prize" id="prize"></div>
</body>
</html>
<script>
    function getCode(){
        var str="0123456789";
        var result="";
        for(var i=0;i<4;i++){
            var index=Math.floor(Math.random()*9);
            result+=str[index];
        }
       prize.innerHTML=result;
       return result;
    }
    var time1=setInterval(function(){
        getCode();
    },1000);

    setTimeout(function(){
        clearInterval(time1);
    },10000)


</script>

倒计时案例:

<!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>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    body {
      background: darkslateblue;
    }

    #time {
      height: 100px;
      line-height: 100px;
      border: 1px dashed yellow;
      text-align: center;
      color: #fff;
      font-size: 26px;
    }
  </style>
</head>

<body>
  <div id="time">

  </div>
  <script>
    /* 
       倒计时:
       目标时间:2021年12月14号
       目标时间-现在的时候=还剩多少时间?
       为了方便计算时间差,我们统一转成到1970年...的时间戳
     */
    function countDown(targetStr) {
      // 目标时间
      var targetTime = new Date(targetStr);
      // 现在的时间
      var nowTime = new Date()
      // 时间差,得出来的是毫秒
      var diffTime = targetTime - nowTime;
      // 把时间差换算成时、分、秒
      var hours = Math.floor(diffTime / (1000 * 60 * 60));
      var minutes = Math.floor((diffTime - hours * 1000 * 60 * 60) / (1000 * 60));
      var seconds = Math.floor((diffTime - hours * 1000 * 60 * 60 - minutes * 60 * 1000) / 1000);
      var result = formatter(hours) + "时" + formatter(minutes) + "分" + formatter(seconds) + "秒";
      return result;
    }
    function formatter(val) {
      return val = Number(val) < 10 ? "0" + val : val;
    }
    var res = countDown("2021-12-24 00:00:00");
    time.innerHTML = res;
    console.log(res)
    setInterval(() => {
      var res = countDown("2021-12-24 00:00:00");
      time.innerHTML = res;
    }, 1000);
  </script>
</body>

</html>