JavaScript Date prototype 属性(长文讲解)
💡一则或许对你有用的小广告
欢迎加入小哈的星球 ,你将获得:专属的项目实战 / 1v1 提问 / Java 学习路线 / 学习打卡 / 每月赠书 / 社群讨论
- 新项目:《从零手撸:仿小红书(微服务架构)》 正在持续爆肝中,基于
Spring Cloud Alibaba + Spring Boot 3.x + JDK 17...
,点击查看项目介绍 ;- 《从零手撸:前后端分离博客项目(全栈开发)》 2 期已完结,演示链接: http://116.62.199.48/ ;
截止目前, 星球 内专栏累计输出 82w+ 字,讲解图 3441+ 张,还在持续爆肝中.. 后续还会上新更多项目,目标是将 Java 领域典型的项目都整一波,如秒杀系统, 在线商城, IM 即时通讯,权限管理,Spring Cloud Alibaba 微服务等等,已有 2900+ 小伙伴加入学习 ,欢迎点击围观
一、前言:为什么需要了解 Date prototype 属性?
在 JavaScript 开发中,日期和时间的处理是一个高频需求场景。无论是计算用户年龄、生成订单时间戳,还是实现倒计时功能,都需要对 Date
对象进行精准操作。然而,许多开发者在使用 Date
对象时,容易陷入时区混乱、月份索引错误等问题。这些问题的根源,往往与对 Date prototype 属性
的理解不足直接相关。
Date prototype 属性
是 JavaScript 日期处理的核心机制之一。它通过 prototype
链式结构,为所有 Date
实例提供了一系列用于解析、操作和格式化时间的工具方法。理解这些属性的使用方式,可以帮助开发者高效、安全地完成时间相关的复杂逻辑。
本文将通过循序渐进的方式,从基础概念讲到实战案例,帮助读者掌握 Date prototype 属性
的核心知识点。
二、基础概念:Date 对象与 prototype 属性
1. Date 对象的创建与基本用法
// 创建当前时间的 Date 实例
const now = new Date();
console.log(now); // 输出类似 "2023-10-05T14:30:45.123Z"
// 通过时间戳创建特定时间
const specificDate = new Date(1696503045123);
console.log(specificDate); // 输出对应的时间
Date
对象的核心功能是将时间信息封装为可操作的对象。开发者可以通过 new Date()
创建表示当前时间的实例,或通过传入时间戳、字符串等参数创建特定时间。
2. prototype 属性的作用
JavaScript 中的 prototype
机制允许为对象定义共享属性和方法。对于 Date
对象来说:
// 通过 prototype 添加全局方法
Date.prototype.getYearDiff = function(targetDate) {
return Math.floor((targetDate - this) / (1000 * 60 * 60 * 24 * 365));
};
const birthDate = new Date('1990-05-15');
console.log(birthDate.getYearDiff(new Date())); // 输出当前年份与 1990 的差值
通过 Date.prototype
,我们可以为所有 Date
实例添加自定义方法。而内置的 Date prototype 属性
则是 JavaScript 引擎预设的、用于获取时间各部分信息的工具。
三、核心属性详解:获取时间的各个维度
1. 获取年份与月份
const date = new Date();
console.log(date.getFullYear()); // 2023(四位数年份)
console.log(date.getMonth()); // 9(0-11,0 表示一月)
getFullYear()
返回四位数的完整年份,避免了getYear()
在千年虫问题中的缺陷。getMonth()
返回 0-11 的数值,需加 1 才能得到实际月份。可以想象成“月份索引”而非“月份值”。
2. 获取日期与星期
console.log(date.getDate()); // 5(当前日期)
console.log(date.getDay()); // 4(0-6,0 表示周日)
getDate()
返回 1-31 的日期数值。getDay()
的结果需结合数组映射来获取星期名称,例如:
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
console.log(days[date.getDay()]); // 输出对应的星期名称
3. 时间部分的获取
console.log(date.getHours()); // 14(0-23 小时制)
console.log(date.getMinutes()); // 30(分钟)
console.log(date.getSeconds()); // 45(秒)
console.log(date.getMilliseconds()); // 123(毫秒)
所有时间获取方法均返回数值型结果,需注意 getHours()
的 24 小时制特性。例如:
// 将小时转换为 12 小时制并添加 AM/PM
function formatTime(date) {
const hours = date.getHours();
return `${hours % 12 || 12}:${date.getMinutes()} ${hours < 12 ? 'AM' : 'PM'}`;
}
4. 时区相关属性
console.log(date.getTimezoneOffset()); // 返回当前时区与 UTC 的分钟差(如北京返回 -480)
getTimezoneOffset()
返回的是 本地时区与 UTC 的分钟差,负值表示比 UTC 时间早的时区。例如:
- 中国标准时间(CST)比 UTC 快 8 小时 →
getTimezoneOffset()
返回 -480 - 美国东部时间(EST)比 UTC 慢 5 小时 → 返回 300
四、进阶方法:格式化与时间计算
1. 标准格式化方法
console.log(date.toISOString()); // "2023-10-05T14:30:45.123Z"
console.log(date.toLocaleString()); // 根据本地设置格式化(如 "10/5/2023, 2:30:45 PM")
toISOString()
总是返回 UTC 时间的 ISO 8601 格式字符串。toLocaleString()
使用本地时区和区域设置进行格式化,但结果可能因环境不同而变化。
2. 时间差计算
const birthday = new Date('1990-05-15');
const now = new Date();
// 计算相差的毫秒数
const diffMs = now - birthday;
console.log(diffMs); // 约 11,000,000,000 毫秒
// 转换为天数
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
console.log(diffDays); // 约 30,136 天
直接相减会得到两个时间戳的毫秒差,需通过单位换算得到天数、小时等。
3. 设置时间值
// 将日期设置为本月第一天
date.setDate(1);
console.log(date); // "2023-10-01T14:30:45.123Z"
// 设置为明天同一时间
date.setDate(date.getDate() + 1);
所有 setXXX()
方法会直接修改原 Date 实例的值,需注意副作用问题。
五、常见陷阱与解决方案
1. 月份从 0 开始的问题
// 错误写法:创建 2023-12-25 的日期
const wrongDate = new Date(2023, 12, 25); // 实际是 2024-01-25
解决方案:始终将月份参数减 1:
const correctDate = new Date(2023, 11, 25); // 正确创建 12 月 25 日
2. 时区偏移的影响
const londonTime = new Date().toLocaleString('en-GB');
const newYorkTime = new Date().toLocaleString('en-US');
console.log(londonTime, newYorkTime); // 可能显示不同时间
解决方案:使用 UTC 方法统一时区:
const utcDate = new Date();
console.log(utcDate.getUTCFullYear(), utcDate.getUTCHours()); // 获取 UTC 标准时间
3. 日期溢出问题
// 创建无效日期
const invalidDate = new Date('2023-13-01'); // 返回 Invalid Date
解决方案:通过 Date.prototype.isValid()
自定义验证:
Date.prototype.isValid = function() {
return !isNaN(this.getTime());
};
const date = new Date('2023-13-01');
if (!date.isValid()) {
console.error('无效日期');
}
六、实战案例:实现年龄计算功能
需求:根据出生日期计算当前年龄
// 1. 定义计算年龄的方法
Date.prototype.getAge = function() {
const now = new Date();
let age = now.getFullYear() - this.getFullYear();
// 检查是否已经过生日
if (
now.getMonth() < this.getMonth() ||
(now.getMonth() === this.getMonth() && now.getDate() < this.getDate())
) {
age--;
}
return age;
};
// 2. 使用示例
const birthDate = new Date('1990-05-15');
console.log(birthDate.getAge()); // 输出当前年份与 1990 的差值(考虑月份)
关键点:
- 通过比较月份和日期判断是否已过生日
- 使用
getFullYear()
获取完整年份 - 通过
prototype
将方法挂载到所有Date
实例
七、高级技巧:自定义日期格式化
案例:实现多语言友好日期显示
// 1. 扩展 Date 原型添加格式化方法
Date.prototype.format = function(locale) {
return this.toLocaleString(locale, {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
};
// 2. 使用不同语言显示
const date = new Date();
console.log(date.format('zh-CN')); // "2023年10月5日 下午2:30"
console.log(date.format('en-US')); // "October 5, 2023, 2:30 PM"
优势:
- 利用浏览器内置的
Intl.DateTimeFormat
API - 通过
locale
参数支持多语言 - 参数对象可定制显示格式(如
hour12: false
切换 24 小时制)
八、结论与建议
通过本文的学习,读者应该掌握了以下关键点:
Date
对象的创建与基本属性prototype 属性
在时间操作中的核心作用- 各种
getXXX()
方法的用法与陷阱 - 通过案例实现年龄计算和格式化功能
建议读者在实践中注意以下事项:
- 时区问题:始终明确操作的是本地时间还是 UTC 时间
- 数据验证:对用户输入的日期进行有效性检查
- 代码复用:通过
Date.prototype
将常用逻辑封装为方法
JavaScript 的 Date prototype 属性
是时间处理的基石,熟练掌握这些知识点将极大提升开发效率。建议读者通过实际项目不断练习,逐步构建自己的日期处理工具库。