// 创建一个Date对象
const now = new Date()
// 获取当前时间戳(毫秒)
const timestamp = now.getTime()
// 获取当前年份
const year = now.getFullYear()
// 获取当前月份(0-11)
const month = now.getMonth()
// 获取当前日期(1-31)
const date = now.getDate()
// 获取当前小时数(0-23)
const hours = now.getHours()
// 获取当前分钟数(0-59)
const minutes = now.getMinutes()
// 获取当前秒数(0-59)
const seconds = now.getSeconds()
// 获取当前毫秒数(0-999)
const milliseconds = now.getMilliseconds()
// 获取当前星期几(0-6,0表示星期日)
const day = now.getDay()
// 将日期格式化为字符串
const formattedDate = now.toDateString()
// 将时间格式化为字符串
const formattedTime = now.toTimeString()
// 将日期和时间格式化为字符串
const formattedDateTime = now.toLocaleString()
// 将日期和时间格式化为ISO字符串
const isoDateTime = now.toISOString()
// 将日期和时间格式化为UTC字符串
const utcDateTime = now.toUTCString()
// 请注意,Date对象的月份从0开始,因此0表示一月,11表示十二月。
高级api
// 获取当前时区偏移量(以分钟为单位)
const offsetMinutes = now.getTimezoneOffset()
// 获取当前时区名称
const timezoneName = Intl.DateTimeFormat().resolvedOptions().timeZone
// 将日期格式化为本地日期字符串
const localDateString = now.toLocaleDateString()
// 将时间格式化为本地时间字符串
const localTimeString = now.toLocaleTimeString()
// 将日期和时间格式化为本地日期时间字符串
const localDateTimeString = now.toLocaleString()
// 将日期格式化为指定格式的字符串
const formattedDate = new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'long', day: 'numeric' }).format(now)
// 将时间格式化为指定格式的字符串
const formattedTime = new Intl.DateTimeFormat('en-US', { hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: true }).format(now)
// 将日期和时间格式化为指定格式的字符串
const formattedDateTime = new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: true }).format(now)
// 将日期和时间格式化为指定时区的字符串
const formattedDateTimeInTimezone = new Intl.DateTimeFormat('en-US', { timeZone: 'America/New_York', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: true }).format(now)
// 请注意,Intl.DateTimeFormat API提供了更多的选项来自定义日期和时间格式。可以根据需要进行调整。