JavaScript日期对象指南:从基础到实战应用
什么是Date对象?
JavaScript中的Date对象用于处理日期和时间。它可以获取年、月、日、时、分、秒等信息,也可以设置这些值,是实现计时器、日历、时间格式化等功能的基石。
// 创建一个表示当前时间的Date对象
let now = new Date();
console.log(now); // 2026-03-13T08:30:00.000Z(具体时间取决于执行时间)
创建Date对象的四种方式
1. 无参数 - 当前时间
let currentDate = new Date();
console.log('当前时间:', currentDate);
2. 毫秒数 - 从1970年1月1日开始的毫秒数
// 1000毫秒 = 1秒
let dateFromMillis = new Date(1000 * 60 * 60 * 24); // 一天的毫秒数
console.log('1970-01-02:', dateFromMillis); // 1970-01-02T00:00:00.000Z
3. 日期字符串
let dateFromString = new Date('2026-03-13T10:30:00');
console.log('从字符串创建:', dateFromString);
// 不同格式的字符串
console.log(new Date('2026-03-13')); // ISO格式
console.log(new Date('March 13, 2026')); // 英文格式
console.log(new Date('2026/03/13')); // 斜杠分隔
4. 多个参数 - 年、月、日、时、分、秒、毫秒
// 年、月(必填,月从0开始,0表示一月)
// 日(可选,默认1)、时(可选,默认0)、分(可选,默认0)、秒(可选,默认0)、毫秒(可选,默认0)
let specificDate = new Date(2026, 2, 13, 10, 30, 0, 0); // 2026年3月13日10:30:00
console.log('指定日期:', specificDate);
// 注意:月份从0开始,所以2表示三月
console.log('一月:', new Date(2026, 0, 1)); // 2026-01-01
console.log('十二月:', new Date(2026, 11, 1)); // 2026-12-01
个人经验:使用多参数构造函数时,最容易犯错的是月份从0开始。我经常在这个问题上踩坑,所以现在习惯在代码中写注释提醒自己,或者使用字符串方式创建日期。
获取日期时间的方法
本地时间获取方法
let date = new Date('2026-03-13T14:30:45');
console.log('getDate() - 日:', date.getDate()); // 13(1-31)
console.log('getDay() - 星期几:', date.getDay()); // 5(0代表周日,5代表周五)
console.log('getFullYear() - 年:', date.getFullYear()); // 2026
console.log('getMonth() - 月:', date.getMonth()); // 2(0-11,2表示三月)
console.log('getHours() - 时:', date.getHours()); // 14(0-23)
console.log('getMinutes() - 分:', date.getMinutes()); // 30(0-59)
console.log('getSeconds() - 秒:', date.getSeconds()); // 45(0-59)
console.log('getMilliseconds() - 毫秒:', date.getMilliseconds()); // 0(0-999)
console.log('getTime() - 时间戳(毫秒):', date.getTime()); // 从1970-01-01开始的毫秒数
世界时间(UTC)获取方法
let date = new Date('2026-03-13T14:30:45+08:00'); // 北京时间
console.log('getUTCDate() - UTC日:', date.getUTCDate()); // 13
console.log('getUTCDay() - UTC星期:', date.getUTCDay()); // 5
console.log('getUTCFullYear() - UTC年:', date.getUTCFullYear()); // 2026
console.log('getUTCHours() - UTC时:', date.getUTCHours()); // 6(北京时间14点,UTC是6点)
console.log('getUTCMinutes() - UTC分:', date.getUTCMinutes()); // 30
设置日期时间的方法
本地时间设置方法
let date = new Date('2026-03-13T10:30:00');
console.log('原始日期:', date);
// 设置日期
date.setDate(15);
console.log('setDate(15):', date); // 改为15日
// 设置月份
date.setMonth(4); // 4表示五月(0-11)
console.log('setMonth(4):', date); // 改为五月
// 设置年份
date.setFullYear(2027);
console.log('setFullYear(2027):', date); // 改为2027年
// 设置小时
date.setHours(14);
console.log('setHours(14):', date); // 改为14点
// 设置分钟
date.setMinutes(45);
console.log('setMinutes(45):', date); // 改为45分
// 设置秒
date.setSeconds(30);
console.log('setSeconds(30):', date); // 改为30秒
世界时间(UTC)设置方法
let date = new Date('2026-03-13T10:30:00');
console.log('原始日期:', date);
date.setUTCDate(20);
date.setUTCMonth(7); // 八月
date.setUTCFullYear(2028);
date.setUTCHours(5);
console.log('设置UTC后:', date);
日期格式化方法
let date = new Date('2026-03-13T14:30:45');
console.log('toString():', date.toString());
// Fri Mar 13 2026 14:30:45 GMT+0800 (我国标准时间)
console.log('toDateString():', date.toDateString());
// Fri Mar 13 2026
console.log('toTimeString():', date.toTimeString());
// 14:30:45 GMT+0800 (我国标准时间)
console.log('toISOString():', date.toISOString());
// 2026-03-13T06:30:45.000Z(ISO格式,UTC时间)
console.log('toUTCString():', date.toUTCString());
// Fri, 13 Mar 2026 06:30:45 GMT
console.log('toJSON():', date.toJSON());
// 2026-03-13T06:30:45.000Z(与toISOString()相同)
console.log('valueOf() - 原始值:', date.valueOf());
// 返回时间戳(毫秒数)
实际应用示例
示例1:获取当前日期(年/月/日格式)
function getCurrentDate() {
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1; // 月份+1
let day = date.getDate();
return `${year}年${month}月${day}日`;
}
console.log('当前日期:', getCurrentDate()); // 2026年3月13日
示例2:获取当前时间(时:分:秒格式)
function getCurrentTime() {
let date = new Date();
let hours = date.getHours().toString().padStart(2, '0');
let minutes = date.getMinutes().toString().padStart(2, '0');
let seconds = date.getSeconds().toString().padStart(2, '0');
return `${hours}:${minutes}:${seconds}`;
}
console.log('当前时间:', getCurrentTime()); // 14:30:45
示例3:计算两个日期之间的天数差
function daysBetween(date1, date2) {
// 转换为Date对象(如果不是)
let d1 = new Date(date1);
let d2 = new Date(date2);
// 计算毫秒差
let diffMs = Math.abs(d2 - d1);
// 转换为天数
let diffDays = Math.ceil(diffMs / (1000 * 60 * 60 * 24));
return diffDays;
}
let start = '2026-03-01';
let end = '2026-03-13';
console.log(`${start}到${end}相差:`, daysBetween(start, end), '天'); // 12天
示例4:判断是否为闰年
function isLeapYear(year) {
let date = new Date(year, 1, 29); // 2月29日
return date.getMonth() === 1; // 如果2月29日存在,则月份仍然是1(二月)
}
console.log('2024年是闰年?', isLeapYear(2024)); // true
console.log('2025年是闰年?', isLeapYear(2025)); // false
console.log('2026年是闰年?', isLeapYear(2026)); // false
示例5:获取某个月的天数
function getDaysInMonth(year, month) {
// month是1-12,需要转换为0-11
return new Date(year, month, 0).getDate();
}
console.log('2026年2月天数:', getDaysInMonth(2026, 2)); // 28
console.log('2026年3月天数:', getDaysInMonth(2026, 3)); // 31
console.log('2024年2月天数:', getDaysInMonth(2024, 2)); // 29(闰年)
高级应用示例
示例6:简单的数字时钟
<!DOCTYPE html>
<html>
<head>
<title>数字时钟示例</title>
</head>
<body>
<h2>当前时间:<span id="clockDisplay"></span></h2>
<script>
function updateClock() {
let now = new Date();
let hours = now.getHours().toString().padStart(2, '0');
let minutes = now.getMinutes().toString().padStart(2, '0');
let seconds = now.getSeconds().toString().padStart(2, '0');
let timeString = `${hours}:${minutes}:${seconds}`;
document.getElementById('clockDisplay').textContent = timeString;
// 每秒更新一次
setTimeout(updateClock, 1000);
}
// 页面加载后启动时钟
window.onload = updateClock;
</script>
</body>
</html>
示例7:日期格式化工具函数
class DateFormatter {
constructor(date = new Date()) {
this.date = date;
}
// 格式:YYYY-MM-DD
toISODate() {
let year = this.date.getFullYear();
let month = (this.date.getMonth() + 1).toString().padStart(2, '0');
let day = this.date.getDate().toString().padStart(2, '0');
return `${year}-${month}-${day}`;
}
// 格式:YYYY年MM月DD日
toChineseDate() {
let year = this.date.getFullYear();
let month = this.date.getMonth() + 1;
let day = this.date.getDate();
return `${year}年${month}月${day}日`;
}
// 格式:HH:MM:SS
toTime() {
let hours = this.date.getHours().toString().padStart(2, '0');
let minutes = this.date.getMinutes().toString().padStart(2, '0');
let seconds = this.date.getSeconds().toString().padStart(2, '0');
return `${hours}:${minutes}:${seconds}`;
}
// 格式:YYYY-MM-DD HH:MM:SS
toDateTime() {
return `${this.toISODate()} ${this.toTime()}`;
}
// 获取星期几(中文)
getWeekdayChinese() {
let weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
return weekdays[this.date.getDay()];
}
}
// 使用示例
let formatter = new DateFormatter();
console.log('ISO日期:', formatter.toISODate()); // 2026-03-13
console.log('中文日期:', formatter.toChineseDate()); // 2026年3月13日
console.log('时间:', formatter.toTime()); // 14:30:45
console.log('日期时间:', formatter.toDateTime()); // 2026-03-13 14:30:45
console.log('星期:', formatter.getWeekdayChinese()); // 星期五
示例8:相对时间(几天前/后)
function getRelativeDate(days) {
let date = new Date();
date.setDate(date.getDate() + days);
return date;
}
function getRelativeDateString(days) {
let date = getRelativeDate(days);
let year = date.getFullYear();
let month = (date.getMonth() + 1).toString().padStart(2, '0');
let day = date.getDate().toString().padStart(2, '0');
if (days === 0) return '今天';
if (days === 1) return `明天 (${year}-${month}-${day})`;
if (days === -1) return `昨天 (${year}-${month}-${day})`;
if (days > 0) return `${days}天后 (${year}-${month}-${day})`;
return `${Math.abs(days)}天前 (${year}-${month}-${day})`;
}
console.log(getRelativeDateString(0)); // 今天
console.log(getRelativeDateString(1)); // 明天 (2026-03-14)
console.log(getRelativeDateString(-1)); // 昨天 (2026-03-12)
console.log(getRelativeDateString(7)); // 7天后 (2026-03-20)
示例9:年龄计算器
function calculateAge(birthDate) {
let today = new Date();
let birth = new Date(birthDate);
let age = today.getFullYear() - birth.getFullYear();
let monthDiff = today.getMonth() - birth.getMonth();
// 如果今年还没过生日,年龄减1
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
age--;
}
return age;
}
console.log('1995-05-15出生的人现在年龄:', calculateAge('1995-05-15'));
console.log('2000-01-01出生的人现在年龄:', calculateAge('2000-01-01'));
示例10:倒计时功能
function countdown(targetDate) {
let target = new Date(targetDate).getTime();
let now = new Date().getTime();
let diff = target - now;
if (diff <= 0) {
return '活动已结束';
}
// 计算天数、小时、分钟、秒
let days = Math.floor(diff / (1000 * 60 * 60 * 24));
let hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((diff % (1000 * 60)) / 1000);
return `剩余:${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
}
// 假设活动在2026-12-31结束
let target = '2026-12-31';
console.log(countdown(target));
// 每秒更新倒计时(在浏览器环境中)
// setInterval(() => {
// console.clear();
// console.log(countdown(target));
// }, 1000);
课程知识要点
-
创建Date对象:四种方式(无参数、毫秒数、日期字符串、多参数)
-
获取方法:getDate()、getDay()、getFullYear()、getMonth()、getHours()等
-
设置方法:setDate()、setMonth()、setFullYear()、setHours()等
-
UTC方法:getUTCDate()、setUTCDate()等(世界时间)
-
格式化方法:toString()、toDateString()、toISOString()、toUTCString()等
-
时间戳:getTime()、valueOf()、Date.now()
-
注意事项:月份从0开始(0-11)、星期从0开始(0代表周日)
开发实践建议
基于多年JavaScript开发经验,我对Date对象的使用建议如下:
// 1. 记住月份从0开始
let date = new Date(2026, 2, 13); // 2026年3月13日(2表示三月)
console.log(date.getMonth()); // 2
// 2. 使用padStart格式化两位数
let hours = date.getHours().toString().padStart(2, '0');
// 3. 使用Date.now()获取当前时间戳
let start = Date.now();
// 执行一些操作...
let end = Date.now();
console.log(`执行时间:${end - start}ms`);
// 4. 避免直接比较日期对象
let d1 = new Date('2026-03-13');
let d2 = new Date('2026-03-13');
console.log(d1 === d2); // false(比较的是对象引用)
console.log(d1.getTime() === d2.getTime()); // true(比较时间戳)
// 5. 使用第三方库处理复杂日期操作
// 对于复杂的时区、国际化、日期计算,可以考虑使用moment.js或date-fns
// 6. 处理用户输入时注意时区问题
function parseDateSafe(dateString) {
// 避免使用new Date(dateString)直接解析,不同浏览器实现有差异
let parts = dateString.split('-');
if (parts.length === 3) {
let [year, month, day] = parts;
return new Date(year, month - 1, day);
}
return new Date(dateString);
}
// 7. 简单的性能测试
function measurePerformance(fn, iterations = 1000000) {
let start = performance performance.now() : Date.now();
for (let i = 0; i < iterations; i++) {
fn();
}
let end = performance performance.now() : Date.now();
return end - start;
}
console.log('执行时间:', measurePerformance(() => {
new Date();
}), 'ms');
Date对象是JavaScript中处理日期时间的基础工具。虽然它有一些设计上的缺陷(比如月份从0开始),但掌握好它的使用方法,足以应对大多数日常开发需求。对于更复杂的日期时间操作,可以考虑使用专门的库如date-fns或Day.js。