JavaScript 时间&计时器

Date类型使用自UTC(国际协调时间)自1970年1月1日0点开始经过的毫秒数来保存日期。
要创建一个日期对象,使用new操作符和Date构造函数即可。var now=new Date();
Date.parse()接收一个表示日期的字符串将返回相应日期的毫秒数。

var time=new Date;
console.log(time);   // Sun Sep 15 2019 20:48:12 GMT+0800 (中国标准时间)
console.log(time.toUTCString());   //"Sun, 15 Sep 2019 12:50:15 GMT"
console.log(time.toDateString());   //"Sun Sep 15 2019"
console.log(time.toISOString());   //"2019-09-15T12:50:41.948Z"
console.log(time.toLocaleDateString());   //"2019/9/15"
console.log(time.toLocaleTimeString());   //"下午8:51:10"
console.log(time.toLocaleString());   //"2019/9/15 下午8:51:23"
console.log(time.toTimeString());    //"20:51:37 GMT+0800 (中国标准时间)"

Date.now()方法可以获取当前时间的毫秒数。可以以此计算代码运行的时间。

var start=Date.now();
var stop=Date.now();
result=stop-start;
console.log(result);

getTime()返回日期毫秒数;
setTime()以毫秒数设置日期;
getFullYear()获取四位数年份;对应的有set
getMonth()获取月份;对应的有set
getDay()获取星期中的星期几;对应的有set
getHours()获取日期中的小时数;对应的有set
getSeconds()获取日期中的秒数;对应的有set

var d = new Date();
var n = d.getTime();
console,log(n);   //Object { 0: 1568552293587 }
var times=new Date();
/!*使用 date中的方法设置*!/
times.setFullYear(2018);//年
times.setDate(3);//天
times.setHours(12);//时
times.setMinutes(59)//分
times.setSeconds(20)//秒
times.setMilliseconds(200);//毫秒
console.log(times);   //Mon Sep 03 2018 12:59:20 GMT+0800 (中国标准时间)

计时器

一秒之后输出1

setTimeout(function (){
        console.log(1);
    },1000);

循环计时器(一秒输出一次1) 需要停止添加 clearTimeout(t); 这样下面的代码只会输出一个1

 var t=null;
    showtime();
    function showtime(){
        console.log(1);
        t=setTimeout("showtime()",1000);
    }
 // clearTimeout(t); 

setTimeout() 方法用于在指定的毫秒数后调用函数或计算表达式。

 var t=null;
    t=setInterval(function(){
        console.log(1);
    },1000);
 //clearInterval(t);

setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。

发布了75 篇原创文章 · 获赞 0 · 访问量 3393

猜你喜欢

转载自blog.csdn.net/E_ISOLATE/article/details/100863470