時間對象是一種復雜數據類型,用來存儲時間
創建時間對象
內置構造函數創建
????????語法:var 時間名=new Date()
var date=new Date()console.log(date) //Wed May 29 2024 16:03:47 GMT+0800 (中國標準時間)
創建指定日期
? ? ? ? 當參數為數字——>在格林威治的時間基礎上增加
? ? ? ? ? ? ? ? 多個數字一次表示年月日時分秒
? ? ? ? 當參數為字符串——>設置指定日期
//格林威治時間 Thu Jan 01 1970 08:00:00 GMT+0800 (中國標準時間)//1.一個參數 在格林威治時間的基礎上加 1000=1svar date1=new Date(1000)console.log(date1) //Thu Jan 01 1970 08:00:01 GMT+0800 (中國標準時間)//2.多個參數 依次表示年月日時分秒 在格林威治時間的基礎上加var date2=new Date(1,2,3)console.log(date2) //Sun Mar 03 1901 00:00:00 GMT+0800 (中國標準時間)//3.當參數為字符串,則是設置具體日期var date3=new Date('2001-12-12 10:10:10')console.log(date3) //Wed Dec 12 2001 10:10:10 GMT+0800 (中國標準時間)var date4=new Date('2001/12/12 10:10:10')console.log(date4) //Wed Dec 12 2001 10:10:10 GMT+0800 (中國標準時間)var date5=new Date('2001/12/12 10:10:10','2002/12/12 10:10:10')console.log(date5) //Invalid Date 無效日期
事件對象方法
var date=new Date('2024/12/2 10:10:10')//獲取年份console.log(date.getFullYear()) //2024//獲取月份 月是從0開始到11結束 0-11——>1-12console.log(date.getMonth()) //返回數字11 // 獲取日期console.log(date.getDate()) //2// 獲取時間console.log(date.getHours()) //10// 獲取分鐘console.log(date.getMinutes()) //10// 獲取秒console.log(date.getSeconds()) //10// 獲取毫秒console.log(date.getMilliseconds()) //0// 獲取星期幾 返回數字0-6分別對應星期日-星期六console.log(date.getDay()) //1// 獲取時間戳——現在距離格林威治時間的毫秒數console.log(date.getTime()) //1733105410000
練習題
練習題1:獲取當前時間編寫一個函數,返回當前的日期和時間字符串,格式為:YYYY-MM-DD-MM-DD HH:mm:ss。
function getCurrentDateTime() {var now = new Date();var year = now.getFullYear();var month = ("0" + (now.getMonth() + 1)).slice(-2);//slice從倒數第2位開始截取var day = ("0" + now.getDate()).slice(-2);var hours = ("0" + now.getHours()).slice(-2);var minutes = ("0" + now.getMinutes()).slice(-2);var seconds = ("0" + now.getSeconds()).slice(-2);return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds; }console.log(getCurrentDateTime());
練習題2:編寫一個函數,輸入任意年月日,輸出該年份的日期是星期幾(例如:0代表周日,1代表周一,以此類推)。
function fn(argDay) {var day = new Date(argDay);return day.getDay();}console.log(fn("2020/12/2")); //3console.log(fn("2023/01/12")); //4console.log(fn("2024/5/27")); //1
練習題3:倒計時創建一個倒計時器函數,接受一個未來的時間(年-月-日 時:分:秒),并實時顯示距離該時間還有多久(以小時、分鐘、秒顯示)。
function fn(d1) {var day1 = new Date();console.log(day1);var day2 = new Date(d1);//兩者相差毫秒數var timer = Math.abs(day1.getTime() - day2.getTime()) / 1000;console.log(timer);//1小時=60分鐘=3600秒 =3600 000毫秒var h = parseInt(timer / 3600);var m = parseInt((timer - h * 3600) / 60);var s = parseInt(timer - h * 3600 - m * 60);return h + ":" + m + ":" + s;}console.log(fn("2024/5/31 20:25:20"));
練習題4:日期比較編寫一個函數,比較兩個日期字符串(格式YYYY-MM-DD),返回哪一個日期更早。
function compareDates(dateStr1, dateStr2) {var date1 = new Date(dateStr1);var date2 = new Date(dateStr2);return date1.getTime() < date2.getTime() ? dateStr1 : dateStr2; }console.log(compareDates("2023-01-01", "2023-12-31"));
練習題5:月份天數編寫一個函數,給定一個年份和月份,返回該月份的天數(考慮閏年)。
var date = new Date(2024, 2, 0); //將日期設置為0即可console.log(date.getDate()); //29