日期对象
日期对象:用来表示时间的对象,可以得到当前的系统时间。
实例化
- 在代码中发现new关键字时,一般将这个操作称为实例化
- 创建一个时间对象并获取时间
- 获得当前时间:
const date = new Date()
- 获得指定时间:
const date = new Date(2005-3-22 08:30:00)
- 获得当前时间:
日期对象的方法
因为日期对象返回的数据我们不能直接使用,所以需要转换为实际开发中常用的格式
方法 | 作用 | 说明 |
---|---|---|
getFullYear() | 获得年份 | 获取四位年份 |
getMonth() | 获得月份 | 取值为0~11 |
getDate() | 获取月份中的每一天 | 不同月份取值不相同 |
getDay() | 获取星期 | 取值为0~6 |
getHours() | 获取小时 | 取值为0~23 |
getMinutes() | 获取分钟 | 取值为0~59 |
getSeconds() | 获取秒 | 取值为0~59 |
例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 300px;
height: 40px;
border: 1px solid #f40;
text-align: center;
line-height: 40px;
}
</style>
</head>
<body>
<div></div>
<script>
const div = document.querySelector('div')
function getMyDate() {
const date = new Date()
return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日${date.getHours() > 9 ? date.getHours() : '0' + (date.getHours())}时${date.getMinutes() > 9 ? date.getMinutes() : '0' + (date.getMinutes())}分${date.getSeconds() > 9 ? date.getSeconds() : '0' + (date.getSeconds())}秒`
}
div.innerHTML = getMyDate()
setInterval(function () {
div.innerHTML = getMyDate()
}, 1000)
</script>
</body>
</html>
时间戳
时间戳是指两个时间相差的毫秒数,它是一种特殊的计量时间的方式,用于实现倒计时效果。
算法:
- 将来的时间戳 - 现在的时间戳 = 剩余时间毫秒数
- 剩余时间毫秒数转换为剩余时间的“年月日分秒”就是倒计时时间
- 比如将来时间戳 2000ms - 现在时间戳 1000ms = 1000ms,1000ms转换就是0小时0分1秒
获取时间戳
getTime()
:获得当前时间戳或指定时间戳
const date = new Date()
console.log(date.getTime())
+new Date()
:获得当前时间戳或指定时间戳,无需实例化
console.log(+new Date())
Date.now()
:只能获得当前时间戳,无需实例化
console.log(Date.now())
高考倒计时案例:
const last = +new Date('2024-6-7 08:00:00')
function down() {
const now = +new Date()
let count = (last - now) / 1000
let d = parseInt(count / 60 / 60 / 24)
let h = parseInt(count / 60 / 60 % 24)
let m = parseInt(count / 60 % 60)
let s = parseInt(count % 60)
return `还剩${d}天${h > 9 ? h : '0' + h}时${m > 9 ? m : '0' + m}分${s > 9 ? s : '0' + s}秒`
}
const div = document.querySelector('div')
div.innerHTML = down()
setInterval(function () {
div.innerHTML = down()
}, 1000)