1 var cDate = new Date(); //获取当前时间
2 var nextDate = new Date('2022/11/08 08:41:35');
3 console.log(nextDate); //定义时间
4
5 getTime() // 返回毫秒数和valueOf()结果一样
6 getMilliseconds()
7 getSeconds() // 返回0-59
8 getMinutes() // 返回0-59
9 getHours() // 返回0-23
10 getDay() // 返回星期几 0周日 6周六
11 getDate() // 返回当前月的第几天
12 getMonth() // 返回月份,从0开始
13 getFullYear() //返回4位的年份 如 2020
1 /*写一个函数,格式化日期对象,返回YYYY-MM-dd hh:mm:ss的形式*/
2 var c = formatDate(new Date());
3 console.log(c);
4 function formatDate(d) {
5 // 1. 验证
6 if(!d instanceof Date){
7 return;
8 }
9
10 // 2. 转化
11 var year = d.getFullYear();
12 var mouth = d.getMonth() + 1;
13 var date = d.getDate();
14 var hour = d.getHours();
15 var minute = d.getMinutes();
16 var second = d.getSeconds();
17
18 // 3. 转化格式 YYYY-MM-dd hh:mm:ss
19 mouth = mouth < 10 ? '0' + mouth : mouth;
20 date = date < 10 ? '0' + date : date;
21 hour = hour < 10 ? '0' + hour : hour;
22 minute = minute < 10 ? '0' + minute : minute;
23 second = second < 10 ? '0' + second : second;
24
25 return year + '-' + mouth + '-' + date + ' ' + hour + ':' + minute + ':' + second;
26 }
<script>
window.onload = function (ev) {
var currentDate, currentTime, nextTime, allTime;
var time = document.getElementById('time');
// 1. 定义将来的时间
var nextDate = new Date('2019/06/06 00:00:00');
// 2. 开启定时器
setInterval(function () {
// 3. 获取当前的时间
currentDate = new Date();
// 4. 获取毫秒数
currentTime = currentDate.getTime();
nextTime = nextDate.getTime();
// console.log(currentTime, nextTime);
// 5. 获取剩余的毫秒
allTime = nextTime - currentTime;
// console.log(allTime);
// 6. 转化
var allSecond = parseInt( allTime / 1000);
// console.log(allSecond);
var d = size(parseInt(allSecond / 3600 / 24)); // 天
var h = size(parseInt(allSecond / 3600 % 24)); // 时
var m = size(parseInt(allSecond / 60 % 60)); // 分
var s = size(parseInt(allSecond % 60)); // 秒
// 7. 注入
time.innerText = '距离端午节放假还剩:' + d + '天' + h + '小时' + m + '分钟' + s + '秒';
}, 1000);
function size(num) {
return num < 10 ? '0' + num : num;
}
}
</script>