Skip to content

日期对象

用来表示日期的对象, 用于获取系统当前时间

获取当前时间

js
const Date = new Date()
console.log(Date)
// Sun Jul 28 2024 10:43:57 GMT+0800 (中国标准时间)

获取指定时间

js
const Date = new Date("2024-08-26 08:26:00")
console.log(Date)
// Mon Aug 26 2024 08:26:00 GMT+0800 (中国标准时间)

时间对象里的方法

方法作用说明
getFullYear()获取年份获取4位年份
getMonth()获取月份取值为0~11
getDate()获取月份中的每一天不同月份的取值也不相同
getDay()获取星期取值为0~6
getHours()获取小时取值为0~23
getMinutes()获取分钟取值为0~59
getSeconds()获取秒取值为0~59
getTime获取时间戳看下面的章节

时间对象里的函数远远不止这些

时间戳

时间戳是指从1970-01-01 00:00:00到现在的毫秒数, 它是一种特殊的计量时间的方法

时间戳可以很方便的进行计算, 例如将来的时间戳 - 现在的时间戳 = 剩余时间的毫秒数

js
// 第一种方法
const Date = new Date()
console.log(Date.getTime())

// 第二种方法
console.log(+new Date())

// 第三种方法
console.log(Date.now())

第一和第二种方法, 都可以通过new Date("2024-08-26 08:26:00")来获取指定时间的时间戳, 而第三种, 只能获取当前时间戳