Date 日期对象
Date 对象用于处理日期和时间。
如何创建日期对象?
格式:
var 变量名 = new Date();
var date = new Date(); // 没有参数的话,自动获取当前计算机时间
console.log(date); // Thu Oct 10 2019 23:26:48 GMT+0800 (中国标准时间)
也可以自己自定义时间:
var date = new Date(2018,7,18,21,36,0,0); // 自定义时间 2018年7月18日21点36分
console.log(date); //Sat Aug 18 2018 21:36:00 GMT+0800 (中国标准时间)
常用的日期对象方法:
getFullYear() 获取当前时间的年份;
getFullYear() //获取当前时间的年份
var date = new Date(2018,7,18,21,36,0,0);
console.log(date.getFullYear()); // 2018
getMonth() 获取当前时间的月份;(0~11) 0代表1月
getMonth() //获取当前时间的月份
var date = new Date(2018,7,18,21,36,0,0); // 0代表1月,这里的7月18就是 8月18
console.log(date.getMonth()); // 7 其实是8月
getDate() 获取当前时间月份的 某一天;(1~31)
getDate() //获取当前时间的月份的某一天
var date = new Date(2018,7,18,4,21,36,0,0);
console.log(date.getDate()); // 18
getDay() 获取当前时间的月份一周的某一天(0~6); 0代表 周日
getDay() //获取当前时间的月份一周的某一天
var date = new Date(2018,7,18,21,36,0,0);
console.log(date.getDay()); // 6 0代表1月,这里的7月18就是 8月18是周六
getHours() 获取当前时间的小时
// getHours() //获取当前时间的小时
var date = new Date(2018,7,18,21,36,0,0);
console.log(date.getHours()); // 21
getMinutes() 获取当前时间的分钟
// getMinutes() 获取当前时间的分钟
var date = new Date(2018,7,18,21,36,0,0);
console.log(date.getMinutes()); // 36
getSeconds() 获取当前时间的 秒
扫描二维码关注公众号,回复:
10376822 查看本文章
//getSeconds() 获取当前时间的 秒
var date = new Date(2018,7,18,21,36,53,0);
console.log(date.getSeconds()); // 53
getTime() 获取从1970年1月日到当前时间的毫秒数(一秒等于1000毫秒)
//getTime() 获取从1970年1月日到当前时间的毫秒数(一秒等于1000毫秒)
var date = new Date(2018,7,18,21,36,53,0);
console.log(date.getTime()); // 1534599413000
倒计时练习:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Date日期对象练习</title>
<style>
*{
margin: 0;
padding: 0px;
}
div {
width:100%;
height:950px;
background-image: url(3.jpg);
background-size: 100%;
background-repeat:no-repeat;
text-align: center;
line-height: 950px;
}
span {
width: 150px;
height: 150px;
border: 3px solid #d4d1b2;
background: rgba(98, 97, 104, 0.6);
text-align: center;
line-height: 150px;
font-size: 80px;
color: #fff;
border-radius: 50px;
display: inline-block;
}
</style>
</head>
<body>
<div>
<!-- <p>距离开奖还剩</p> -->
<span id="h1"></span>
<span id="m1"></span>
<span id="s1"></span>
</div>
<script>
// 如何创建日期对象? 通过new Date来创建日期对象
// var a = new Date();
// console.log(a);
var staTime = new Date(2019, 9, 11, 20, 30, 0, 0); // 创建结束的时间点
var endTime = staTime.getTime(); // 获取 结束时间到1970年之间的时间
var a;
var time, h, m, s;
setInterval(function () {
a = new Date(); // 获取当前时间点
var curTime = a.getTime(); // 获取当前时间点到1970的毫秒数;
time = parseInt((endTime - curTime) / 1000); // 获取结束时间到当前时间之间的秒数
h = parseInt(time / 3600); // 小时
m = parseInt(time / 60) - h * 60; // 分钟
s = time - h * 3600 - m * 60; // 秒
h1.innerHTML = h;
m1.innerHTML = m;
s1.innerHTML = s;
}, 1000)
</script>
</body>
</html>