JavaScript 中Date对象详解(全面版)


一、创建 Date 实例

1)无参:当前时间

const now = new Date()

2)传入时间戳(毫秒)

const d1 = new Date(1723536000000)

3)传入时间字符串

const d2 = new Date('2025-07-14T10:30:00')

4)传入年月日时分秒(注意:月份从0开始)

const d3 = new Date(2025, 6, 14, 10, 30, 0)  // 2025-07-14 10:30:00

二、常用实例方法

🕒 获取时间

方法 说明
getFullYear() 获取年份
getMonth() 获取月份(0\~11)
getDate() 获取日(1\~31)
getDay() 获取星期(0\~6,周日0)
getHours() 获取小时(0\~23)
getMinutes() 获取分钟(0\~59)
getSeconds() 获取秒数
getMilliseconds() 毫秒(0\~999)
getTime() 毫秒级时间戳
getTimezoneOffset() 本地与 UTC 的分钟差

🕕 设置时间

方法 说明
setFullYear(year) 设置年份
setMonth(month) 设置月份
setDate(day) 设置日期
setHours(hour) 设置小时
setMinutes(minute) 设置分钟
setSeconds(second) 设置秒数
setMilliseconds(ms) 设置毫秒
setTime(ms) 设置时间戳

三、格式化输出

1)toString()

new Date().toString()
// "Mon Jul 14 2025 10:30:00 GMT+0800 (中国标准时间)"

2)toDateString()

new Date().toDateString()
// "Mon Jul 14 2025"

3)toTimeString()

new Date().toTimeString()
// "10:30:00 GMT+0800 (中国标准时间)"

4)toISOString()

new Date().toISOString()
// "2025-07-14T02:30:00.000Z"

5)toLocaleString()

本地化日期时间:

new Date().toLocaleString()
// "2025/7/14 10:30:00"

四、静态方法

方法 作用
Date.now() 当前时间戳(毫秒)
Date.parse(str) 解析时间字符串,返回时间戳
Date.UTC(...) 返回 UTC 时间戳
Date.now()         // 类似 new Date().getTime()
Date.parse('2025-07-14T10:30:00')  // 毫秒时间戳

五、注意点

  • 月份从 0 开始(0=1月,11=12月)。
  • getDay() 周日是 0。
  • 时区差:getTimezoneOffset(),例如中国是 -480 分钟。

六、常见应用

1)获取时间戳

+new Date()
new Date().getTime()
Date.now()

2)格式化 yyyy-mm-dd

function formatDate(date) {
    let y = date.getFullYear()
    let m = String(date.getMonth() + 1).padStart(2, '0')
    let d = String(date.getDate()).padStart(2, '0')
    return `${y}-${m}-${d}`
}

3)计算两个时间差

let t1 = new Date('2025-07-14')
let t2 = new Date('2025-07-20')
let diffDays = (t2 - t1) / (1000 * 60 * 60 * 24)  // 差几天

总结

  • Date 能创建、读取、设置、格式化、计算时间。
  • 格式化输出建议配合 toLocaleString,也可自定义。
  • 时间戳操作高效,计算差值便捷。

JavaScript函数中call apply bind的讲解说明

BOM(浏览器对象模型)详细学习清单与说明

评 论
请登录后再评论