JavaScript Date对象之获取日期、时间与年份完全指南
作者:椰子女士的面条
Date对象是JavaScript中的一个核心内置对象,它允许我们创建、操作和格式化日期和时间,这篇文章主要介绍了JavaScript Date对象之获取日期、时间与年份的相关资料,需要的朋友可以参考下
一、Date 对象基础
JavaScript 的 Date 对象是处理日期和时间的内置对象,它可以表示从 1970 年 1 月 1 日 UTC(协调世界时)至今的毫秒数。
创建 Date 实例
// 1. 获取当前日期和时间 const now = new Date(); // 2. 通过时间戳创建 const timestamp = 1634567890123; // 毫秒数 const dateFromTimestamp = new Date(timestamp); // 3. 通过日期字符串创建 const dateFromString = new Date("2023-10-20T14:30:00"); // 4. 通过年、月、日等参数创建 // 注意:月份是从0开始计数的(0=一月,11=十二月) const specificDate = new Date(2023, 9, 20, 14, 30, 0);
二、获取当前日期和时间
1. 获取完整日期时间字符串
const now = new Date(); // 1. 本地日期时间字符串 console.log(now.toString()); // 示例输出: "Fri Oct 20 2023 14:30:45 GMT+0800 (中国标准时间)" // 2. ISO 格式字符串 console.log(now.toISOString()); // 示例输出: "2023-10-20T06:30:45.000Z" // 3. 本地日期字符串 console.log(now.toDateString()); // 示例输出: "Fri Oct 20 2023" // 4. 本地时间字符串 console.log(now.toTimeString()); // 示例输出: "14:30:45 GMT+0800 (中国标准时间)" // 5. 本地化格式 console.log(now.toLocaleString()); // 示例输出: "2023/10/20 14:30:45" console.log(now.toLocaleDateString()); // 示例输出: "2023/10/20" console.log(now.toLocaleTimeString()); // 示例输出: "14:30:45"
2. 获取各个日期时间组件
const now = new Date(); // 获取年份(4位数) const fullYear = now.getFullYear(); // 2023 // 获取月份(0-11) const month = now.getMonth(); // 9 (表示十月) // 获取日期(1-31) const date = now.getDate(); // 20 // 获取星期(0-6,0表示星期日) const day = now.getDay(); // 5 (表示星期五) // 获取小时(0-23) const hours = now.getHours(); // 14 // 获取分钟(0-59) const minutes = now.getMinutes(); // 30 // 获取秒数(0-59) const seconds = now.getSeconds(); // 45 // 获取毫秒(0-999) const milliseconds = now.getMilliseconds(); // 0 // 获取时间戳(自1970年1月1日以来的毫秒数) const timestamp = now.getTime(); // 1697783445000
三、获取当前年份的多种方式
1. 基本方法
const currentYear = new Date().getFullYear(); console.log(currentYear); // 2023
2. 其他获取年份的方法
const now = new Date(); // 方法1: getFullYear() (推荐) const year1 = now.getFullYear(); // 2023 // 方法2: 从ISO字符串中提取 const year2 = now.toISOString().slice(0, 4); // "2023" // 方法3: 使用Intl.DateTimeFormat const year3 = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(now); // "2023" // 方法4: 从本地化字符串中提取 const year4 = now.toLocaleDateString('zh-CN', { year: 'numeric' }); // "2023" // 不推荐的方法: getYear() (已废弃) const yearOld = now.getYear(); // 123 (2023-1900)
四、日期格式化实用技巧
1. 自定义格式化函数
function formatDate(date) { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; } console.log(formatDate(new Date())); // "2023-10-20"
2. 格式化为更易读的形式
function formatNiceDate(date) { const months = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']; return `${date.getFullYear()}年 ${months[date.getMonth()]} ${date.getDate()}日`; } console.log(formatNiceDate(new Date())); // "2023年 十月 20日"
3. 相对时间显示
function timeAgo(date) { const now = new Date(); const seconds = Math.floor((now - date) / 1000); if (seconds < 60) return `${seconds}秒前`; if (seconds < 3600) return `${Math.floor(seconds/60)}分钟前`; if (seconds < 86400) return `${Math.floor(seconds/3600)}小时前`; const days = Math.floor(seconds/86400); return days < 30 ? `${days}天前` : formatDate(date); } console.log(timeAgo(new Date(Date.now() - 5000))); // "5秒前" console.log(timeAgo(new Date(Date.now() - 3600000))); // "1小时前" console.log(timeAgo(new Date(2023, 9, 1))); // "2023-10-01"
五、时区处理
1. 获取UTC时间
const now = new Date(); // 获取UTC时间组件 const utcHours = now.getUTCHours(); const utcMinutes = now.getUTCMinutes(); // 转换为UTC字符串 console.log(now.toUTCString()); // "Fri, 20 Oct 2023 06:30:45 GMT"
2. 时区转换
function convertTimezone(date, timezone) { return new Date(date.toLocaleString('en-US', { timeZone: timezone })); } // 将当前时间转换为纽约时间 const nyTime = convertTimezone(new Date(), 'America/New_York'); console.log(nyTime.toLocaleString()); // "10/20/2023, 2:30:45 AM" (假设北京时间是14:30)
六、日期计算
1. 日期加减
// 加5天 const date = new Date(); date.setDate(date.getDate() + 5); // 减3个月 date.setMonth(date.getMonth() - 3); // 加2年 date.setFullYear(date.getFullYear() + 2);
2. 计算日期差
function dateDiffInDays(date1, date2) { const diffTime = Math.abs(date2 - date1); return Math.floor(diffTime / (1000 * 60 * 60 * 24)); } const start = new Date(2023, 0, 1); // 2023年1月1日 const end = new Date(2023, 9, 20); // 2023年10月20日 console.log(dateDiffInDays(start, end)); // 292天
七、最佳实践与注意事项
月份从0开始:一月是0,十二月是11
使用getFullYear():不要使用已废弃的getYear()
处理时区问题:明确业务是否需要考虑时区
日期不可变性:进行日期计算时最好创建新对象
// 推荐做法 const newDate = new Date(oldDate.getTime()); newDate.setDate(newDate.getDate() + 1); // 不推荐 - 修改了原对象 oldDate.setDate(oldDate.getDate() + 1);
性能考虑:频繁创建Date对象会影响性能
使用库处理复杂逻辑:考虑使用moment.js、date-fns等库处理复杂日期操作
八、现代JavaScript日期处理
1. Temporal提案(未来标准)
// 提案阶段,未来可能的标准API const today = Temporal.Now.plainDateISO(); console.log(today.year); // 2023 console.log(today.month); // 10 (不再是0-based) console.log(today.day); // 20
2. 使用第三方库
// 使用date-fns库示例 import { format, addDays, differenceInDays } from 'date-fns'; const today = new Date(); console.log(format(today, 'yyyy-MM-dd')); // "2023-10-20" const tomorrow = addDays(today, 1); console.log(differenceInDays(tomorrow, today)); // 1
总结
JavaScript的Date对象提供了丰富的API来处理日期和时间:
获取当前日期时间:
new Date()
获取年份:
getFullYear()
(推荐)获取日期组件:
getDate()
,getMonth()
,getHours()
等格式化显示:
toLocaleString()
,toISOString()
等方法日期计算:通过
setDate()
,setFullYear()
等方法进行
记住处理日期时的常见陷阱(如月份从0开始),对于复杂场景可以考虑使用专门的日期库。随着Temporal提案的推进,未来JavaScript的日期处理将变得更加简单和强大。