日期对象
掌握 Date 日期对象的使用,动态获取当前计算机的时间。
ECMAScript 中内置了获取系统时间的对象 Date,使用 Date 时与之前学习的内置对象 console 和 Math 不同,它需要借助 new 关键字才能使用。
实例化
<script>
// 实例化 new
// 1.获得当前的时间
const date = new Date()
console.log(date);
// 2. 获得指定时间
const date1 = new Date('2022-5-1 08:30:00')
console.log(date1);
</script>
方法
<script>
// 获得日期对象
const date = new Date()
// 年
console.log(date.getFullYear());
// 月
console.log(date.getMonth() + 1);
// 日
console.log(date.getDate())
// 星期
console.log(date.getDay())
// 小时
console.log(date.getHours())
// 分
console.log(date.getMinutes())
// 秒
console.log(date.getSeconds())
// 把get换成set就是设置时间
date.setFullYear(2020)
console.log(date); //Wed Apr 22 2020 16:05:20 GMT+0800 (中国标准时间)
//星期是不能更改的,因为星期是固定的
</script>
getFullYear 获取四位年份
getMonth 获取月份,取值为 0 ~ 11
getDate 获取月份中的每一天,不同月份取值也不相同
getDay 获取星期,取值为 0 ~ 6
getHours 获取小时,取值为 0 ~ 23
getMinutes 获取分钟,取值为 0 ~ 59
getSeconds 获取秒,取值为 0 ~ 59
时间戳
时间戳是指1970年01月01日00时00分00秒起至现在的总秒数或毫秒数,它是一种特殊的计量时间的方式。
注:ECMAScript 中时间戳是以毫秒计的。
<script>
// 第一种方法 getTime() 需要实例化
const date = new Date()
// console.log(date.getTime());
// 第二种 +new Date
// console.log(+new Date());
// 第三种 只可以获取当前的时间戳
// console.log(Date.now());
// 可以返回指定的时间
console.log(+new Date('2020-5-1 09:30:00'));
console.log(date.getTime('2020-5-1 09:30:00'));
</script>
获取时间戳的方法,分别为 getTime 和 Date.now 和 +new Date()