JS內建物件—— Date物件
阿新 • • 發佈:2022-05-17
//(1)獲取時間
var date1 = new Date(); //沒有引數,返回當前時間
console.log(date1);
var date2 = new Date('2020-6-3 8:30:8'); //沒有引數,返回當前時間 console.log(date2); //(2)列印日期,以'今天是xx年xx月xx日星期x'的形式 var date = new Date(); var year = date.getFullYear(); //返回當期日期的年 var month = date.getMonth() + 1; //月,0-11,返回的月份小1個月 var dates = date.getDate(); //幾號 var day = date.getDay(); //週一返回的是1 週六返回的是6 但是週日返回的是0 var h = date.getHours(); //時 h = h < 10 ? '0' + h : h var m = date.getMinutes(); //分 m = m < 10 ? '0' + m : m var s = date.getSeconds(); //秒 s = s < 10 ? '0' + s : s var arrday = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']; console.log('今天是' + year + '年' + month + '月' + dates + '日' + arrday[day] + ' ' + h + ':' + m + ":" + s); //(3)獲取時間戳——距離1970.1.1總的毫秒數 console.log(date.valueOf()); //法一 console.log(date.getTime()); //法二 var date3 = +new Date(); //法三 console.log(date3); console.log(Date.now()); //法四,H5新增 //倒計時案例 function countDown(time) { var nowTime = +new Date(); //返回的是當前時間戳 var inputTime = +new Date(time); //返回的是輸入時間戳 var times = (inputTime - nowTime) / 1000; //剩餘時間總的秒數 var days = parseInt(times / 60 / 60 / 24); //天 var hours = parseInt(times / 60 / 60 % 24); //時 var mintues = parseInt(times / 60 % 60); //分 var seconds = parseInt(times % 60); //秒 return days + '天' + hours + '時' + mintues + '分' + seconds + '秒' } console.log(countDown('2022-5-16 18:00:00'));