JavaScript--Date对象
·
Date 对象
创建日期对象
// 当前时间
const now = new Date();
console.log(now); // 当前时间的Date对象
// 指定时间戳(毫秒)
const timestamp = new Date(1704067200000);
console.log(timestamp); // 2024-01-01T00:00:00.000Z
// 指定日期字符串
const dateStr = new Date('2024-01-15T10:30:00');
console.log(dateStr);
// 指定年月日等参数
const specificDate = new Date(2024, 0, 15, 10, 30, 0); // 月份从0开始
console.log(specificDate); // 2024-01-15T02:30:00.000Z
常用方法
const date = new Date();
// 获取时间组件
console.log(date.getFullYear()); // 2024
console.log(date.getMonth()); // 0 (0-11,0表示一月)
console.log(date.getDate()); // 15 (1-31)
console.log(date.getDay()); // 1 (0-6,0表示周日)
console.log(date.getHours()); // 10 (0-23)
console.log(date.getMinutes()); // 30 (0-59)
console.log(date.getSeconds()); // 45 (0-59)
console.log(date.getMilliseconds());// 123 (0-999)
// 设置时间组件
date.setFullYear(2025);
date.setMonth(5); // 六月
date.setDate(20);
// 时间戳
console.log(date.getTime()); // 毫秒时间戳
console.log(Date.now()); // 当前时间戳
// 格式化
console.log(date.toString()); // "Mon Jun 20 2025 10:30:45 GMT+0800"
console.log(date.toISOString()); // "2025-06-20T02:30:45.123Z"
console.log(date.toLocaleString());// "2025/6/20 10:30:45"
格式化时间
// 格式化日期
function formatDate(date) {
return `${date.getFullYear()}-${(date.getMonth() + 1)
.toString()
.padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
}
console.log(formatDate(new Date())); // "2025-9-1"
更多推荐


所有评论(0)