JS日期和時間

  1. 語法
    var Time = new Date()

  2. 日期/時間的組件方法:
    Date.setTime() // 設置毫秒時間
    Date.setFullYear() // 設置日期的年份,必須是4位數(shù)
    Date.setMonth() // 設置日期的月份, 傳入的月份值必須大于0,超過11則增加年份 。
    Date.setDate() // 設置日期月份中的天數(shù),如果傳入的值超過了該月中的天數(shù),則增加月份 。
    Date.setDay() // 沒有這個方法
    Date.setHours() // 設置日期中的小時數(shù),傳入的數(shù)值超過23則增加月份中的天數(shù) 。
    Date.setMinutes() // 設置日期中的分鐘數(shù),傳入的值超過59則增加小時數(shù)
    Date.setSeconds() // 設置日期中的秒數(shù),傳入的值超過59則增加分鐘數(shù)
    Date.setMilliseconds() // 返回日期中的毫秒數(shù)

  3. 獲取時間

var date = new Date();
console.log(date);

// 返回毫秒時間
console.log(date.getTime());
// 返回四位數(shù)的年份
console.log(date.getFullYear());

// 返回日期的月份   0 表示 一月 ;  
console.log(date.getMonth());

// 返回日期月份的天數(shù) (1-31)
console.log(date.getDate());

// 返回日期的周幾   0 表示 星期日 ;  
console.log(date.getDay());

// 返回日期中的小時數(shù)  0-23
console.log(date.getHours());

// 返回日期中的分鐘數(shù)  0-59
console.log(date.getMinutes());

// 返回日期中的秒數(shù)  0-59
console.log(date.getSeconds());

二、 定時器
設置定時器

var timer = setInterVal();//會不停調(diào)用
var timer = setTimeout(函數(shù)表達式,毫秒數(shù))  //  只執(zhí)行一次

清除定時器

clearInterval(timer);
clearTimeout(timer)
timer = null;

例如:

var i = 0;
var timer = setInterVal(function () {
    // 每秒執(zhí)行一次
    i++;
    console.log(i);
    if (i === 5) {
        clearInterval(timer);
        timer = null;
    }
}, 1000);


var timer2 = setTimeout(function () {
    console.log('tianchu');
    clearTimeout(timer2);
    timer2 = null;
}, 2000);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容