day7JS-时间对象

1. 时间对象

1.1 作用

Date 对象用于处理日期和时间。

1.2 创建时间对象

写法一:
new Date():获取系统当前时间

写法二:传参,字符串,字符串的样式必须是xxxx-xx-xx xx:xx:xx的样式
new Date(""):获取指定的时间。

写法三:使用“逗号”隔开传参,该方法如果是多位数,0不能做开头
new Date(xxxx,x,x,x,x,x):获取指定的时间。

案例:

<body>
    <script>
        //写法一:
        let date1 = new Date();
        console.log(date1);//Wed Aug 14 2024 10:16:31 GMT+0800 (中国标准时间),是一个时间对象

        //写法二:
        let date2 = new Date("2014-08-14 12:00:00");
        console.log(date2);//Thu Aug 14 2014 12:00:00 GMT+0800 (中国标准时间)

        //写法三:
        let date3 = new Date(2014, 8, 12, 12, 0, 0);
        console.log(date3);//Fri Sep 12 2014 12:00:00 GMT+0800 (中国标准时间)
    </script>
</body>

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

getFullYear(); :获取

getMonth(); :获取月份是从0到11,代表1月到12月。0代表1月份,11代表12月份。

getDate(); :获取期。

getDay(); :星期几星期几是从0到6,代表周日到到周六

getHours(); :

getMinutes(); :

getSeconds(); :

getMilliseconds(); :毫秒

getTime(); :获取当前日期1970年1月1号 00:00:00 之间的毫秒差。

toLocaleString(); :获取到的是字符串的年月日时分秒,例如:"2024/1/26 上午10:15:50"。

toLocaleDateString(); :获取到是字符串的年月日,例如:"2024/1/26"。

toLocaleTimeString(); :获取到的是字符串的时分秒,例如:上午10:18:28。

<body>
    <script>
        let date = new Date();
        console.log(date);//Wed Aug 14 2024 09:57:58 GMT+0800 (中国标准时间)
        console.log(date.getFullYear());
        console.log(date.getMonth());
        console.log(date.getDate());
        console.log(date.getDay());
        console.log(date.getHours());
        console.log(date.getMinutes());
        console.log(date.getSeconds());
        console.log(date.getMilliseconds());
        console.log(date.getTime());
        console.log(date.toLocaleString());
        console.log(date.toLocaleDateString());
        console.log(date.toLocaleTimeString());
    </script>
</body>

1.4 案例:钟表

<body>
    <h1 id="getClock">时钟:</h1>
    <script>
        function getClock() {
            let presentTime = new Date;
            let year = presentTime.getFullYear();//年
            let month = presentTime.getMonth() + 1;//月
            let date = presentTime.getDate();//日

            let day = presentTime.getDay();//星期几
            let weekStr = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]
            let week = weekStr[day];

            let hours = presentTime.getHours();//时
            let minutes = presentTime.getMinutes();//分
            let seconds = presentTime.getSeconds();//秒

            let result = `${year}年${addZero(month)}月${addZero(date)}日${week}${addZero(hours)}时${addZero(minutes)}分${addZero(seconds)}秒`;
            return result;
        }

        let getClocks = getClock();
        //获取标签
        let h1 = document.querySelector("h1");
        //向标签中写入内容
        h1.innerHTML = `时钟:${getClocks}`;

        // 补0函数
        function addZero(n) {
            return n >= 10 ? n : "0" + n;
        }
    </script>
</body>

补0方法详解:

方法一:

function addZero(n) {
            return n >= 10 ? n : "0" + n;
        }

方法二:转化为字符串,判断长度。

function addZero(n) {
            return n.toString().length >= 2 ? n : "0" + n;
        }

方法三:补0,使用substr() slice() 到着截取。

function addZero(n) {
            // return ("0" + n).substr(-2, 2);
            return ("0" + n).slice(-2);
        }

2. 定时器

2.1 定时器的分类

  • 一次性定时器 :例如:倒计时。
  • 周期性定时器:例如:轮播图。

2.2 定时器的使用步骤

步骤一:先创建一个变量未来接收定时器。

步骤二:使用定时器

步骤三:使用完毕后释放

2.3 setTimeOut(一次性定时器 

         在一定的时间后,去执行某些事情,是单次调用

setTimeOut(回调函数,周期时间,...)

注意!!!

第一个参数:回调函数

第二个参数:周期时间,单位是毫秒

第三个参数:给回调函数传实参(参数1,参数2,...),该参数可省略。

<body>
    <h1>标题</h1>
    <script>
        // 步骤一:先创建一个变量未来接收定时器
        let timer = null;
        //步骤二:使用定时器
        timer = setTimeout(() => {
            let h1 = document.querySelector("h1");
            h1.innerHTML = "你好"
            // 步骤三:使用完毕后释放
            clearTimeout(timer);
            timer = null;
        }, 1000)
    </script>
</body>

2.4 setInterval(周期性定时器 

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

setInterval(回调函数,周期时间,...)

注意!!!

第一个参数:回调函数

第二个参数:周期时间,单位是毫秒

第三个参数:给回调函数传实参(参数1,参数2,...),该参数可省略。

<body>
    <h1>标题</h1>
    <script>
        // 步骤一:先创建一个变量未来接收定时器
        let timer = null;
        let num = 0;
        let h1 = document.querySelector("h1");
        //步骤二:使用定时器
        timer = setInterval(() => {
            num++;
            h1.innerHTML = "标题" + num;
            // 步骤三:如果想要定时器停止,要加判断条件,使用完毕后释放
            if (num >= 5) {
                clearInterval(timer);
                timer = null;
            }
        }, 500);
    </script>
</body>

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

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(time2)=====>2
console.log(time3)=====>3

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

3. 清除定时器的方法

clearTimeout(定时器变量名)一次性定时器的清除定时器的方法。

clearInterval(定时器变量名)周期性定时器的清除定时器的方法。

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

clearTimeout(time1);


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

clearInterval(time2)

4. 练习

4.1 练习1

        做一个抽奖程序,页面中有一个区域显示中奖人员的编号,在JS中写一段代码,要求每隔1秒中随机创建一个四位的数字(每一位数字的取值范围0-9),当10秒结束后,结束定时器,最后显示的四位数字即是中奖的号码。

<body>
    <h1>中奖人员编号:</h1>
    <button id="btn">抽奖</button>
    <script>

        /* 做一个抽奖程序,页面中有一个区域显示中奖人员的编号,
            在JS中写一段代码,要求每隔1秒中随机创建一个四位的数字(每一位数字的取值范围0-9),
            当10秒结束后,结束定时器,最后显示的四位数字即是中奖的号码 */

        //创建4为随机数
        function getRandom() {
            let code = "";
            for (let i = 0; i < 4; i++) {
                code += Math.floor(Math.random() * 10);
            }
            return code;
        }

        let h1 = document.querySelector("h1")

        // 点击,开始抽奖
        btn.onclick = function () {
            //每一秒执行函数生成随机数
            let timer1 = setInterval(() => {
                h1.innerHTML = getRandom();
            }, 1000);

            //10秒后暂停定时器
            let timer2 = setInterval(() => {
                clearInterval(timer1);
                timer1 = null;

                clearInterval(timer2);
                timer2 = null;
            }, 10000);

        }
    </script>
</body>

4.2 练习2

前置知识:随机数

Math.random() :获取0~1 之间的随机数(大于等于0,小于1)。

1. 包前包后 [ min,max ]

Math.round( Math.random() * (max - min) )+ min

parseInt( Math.random() * ( max - min + 1) + min )

Math.floor(Math.random() * (max- min +1 ))+ min

2. 包前不包后 [ min,max )

Math.floor( Math.random() * (max - min) )+ min

3. 不包前包后( min,max ]

Math.ceil( Math.random() * (max - min) )+ min

4. 在JS中时间减时间的运算得到的是一个时间戳。把时间戳换算成天,时,分,秒的公式如下:

//天
let date = Math.floor(diffTime / (24 * 60 * 60 * 1000));
//小时
let hours = Math.floor(diffTime / (60 * 60 * 1000) % 24);
//分
let minutes = Math.floor(diffTime / (60 * 1000) % 60);
//秒
let seconds = Math.floor(diffTime / 1000 % 60);

 倒计时案例:

<body>
    <h1></h1>
    <script>
        let goalTime = new Date("2024-08-15 16:16:00");
        function getTime() {
            let nowTime = new Date();
            let diffTime = goalTime - nowTime;
            if (diffTime <= 0) {
                clearInterval(timer);
                timer = null;
                return "倒计时结束"
            }
            let date = Math.floor(diffTime / (24 * 60 * 60 * 1000));
            let hours = Math.floor(diffTime / (60 * 60 * 1000) % 24);
            let minutes = Math.floor(diffTime / (60 * 1000) % 60);
            let seconds = Math.floor(diffTime / 1000 % 60);
            let str = `${date <= 0 ? "" : date + "天"}${hours <= 0 ? "" : hours + "时"}${minutes <= 0 ? "" : minutes + "分"}${seconds <= 0 ? "" : seconds + "秒"}`;
            return str;
        }
        let h1 = document.querySelector("h1");
        h1.innerHTML = `距离2024-08-15 16:16:00还有:${getTime()}`;

        let timer = setInterval(() => {
            h1.innerHTML = `距离2024-08-15 16:16:00还有:${getTime()}`;
        }, 1000);
    </script>
</body>

  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值