Date对象基础
2025年3月7日大约 11 分钟
Date对象基础
JavaScript的Date对象是处理日期和时间的核心工具。本文将介绍如何创建Date对象、获取和设置日期时间的各个部分,以及日期的基本格式化。
Date对象概述
JavaScript的Date对象用于处理日期和时间,基于Unix时间戳(从1970年1月1日UTC午夜开始计算的毫秒数)。Date对象提供了多种方法来创建、操作和格式化日期时间。
创建Date对象
有多种方式可以创建Date对象:
1. 当前日期时间
// 创建表示当前日期和时间的Date对象
const now = new Date();
console.log(now); // 例如:Mon May 15 2023 14:30:25 GMT+0800 (中国标准时间)
2. 指定日期时间
// 从时间戳创建(毫秒数)
const date1 = new Date(1684123825000);
console.log(date1); // 对应时间戳的日期
// 从日期字符串创建
const date2 = new Date('2023-05-15T14:30:25');
console.log(date2);
// 从年、月、日等值创建
// 注意:月份从0开始(0表示一月,11表示十二月)
const date3 = new Date(2023, 4, 15, 14, 30, 25); // 2023年5月15日 14:30:25
console.log(date3);
// 创建特定日期(只有年月日)
const date4 = new Date(2023, 4, 15); // 2023年5月15日 00:00:00
console.log(date4);
3. 复制现有Date对象
const original = new Date();
const copy = new Date(original);
console.log(copy); // 与original相同的时间
获取日期时间信息
Date对象提供了多种方法来获取日期和时间的各个部分:
获取年、月、日
const date = new Date(2023, 4, 15, 14, 30, 25);
// 获取年份
console.log(date.getFullYear()); // 2023
// 获取月份(0-11,0表示一月)
console.log(date.getMonth()); // 4(表示五月)
// 获取日(1-31)
console.log(date.getDate()); // 15
// 获取星期几(0-6,0表示星期日)
console.log(date.getDay()); // 1(表示星期一)
获取时、分、秒、毫秒
const date = new Date(2023, 4, 15, 14, 30, 25, 500);
// 获取小时(0-23)
console.log(date.getHours()); // 14
// 获取分钟(0-59)
console.log(date.getMinutes()); // 30
// 获取秒数(0-59)
console.log(date.getSeconds()); // 25
// 获取毫秒数(0-999)
console.log(date.getMilliseconds()); // 500
获取时间戳
const date = new Date(2023, 4, 15);
// 获取时间戳(自1970年1月1日UTC以来的毫秒数)
console.log(date.getTime()); // 例如:1684080000000
// 另一种获取时间戳的方法
console.log(Date.now()); // 当前时间的时间戳
获取UTC时间(世界协调时间)
const date = new Date(2023, 4, 15, 14, 30, 25);
// 获取UTC年份
console.log(date.getUTCFullYear()); // 2023
// 获取UTC月份
console.log(date.getUTCMonth()); // 4
// 获取UTC日期
console.log(date.getUTCDate()); // 15
// 获取UTC小时(可能与本地时间不同,取决于时区)
console.log(date.getUTCHours()); // 例如:6(如果本地是UTC+8时区)
设置日期时间信息
Date对象也提供了方法来修改日期和时间的各个部分:
设置年、月、日
const date = new Date(2023, 4, 15);
// 设置年份
date.setFullYear(2024);
console.log(date); // 2024年5月15日
// 设置月份
date.setMonth(0); // 设置为一月
console.log(date); // 2024年1月15日
// 设置日期
date.setDate(1);
console.log(date); // 2024年1月1日
// 设置日期还可以实现月份的进位
const lastDay = new Date(2023, 0, 31); // 2023年1月31日
lastDay.setDate(lastDay.getDate() + 1); // 加1天
console.log(lastDay); // 2023年2月1日(自动进入下个月)
设置时、分、秒、毫秒
const date = new Date(2023, 4, 15);
// 设置小时
date.setHours(12);
console.log(date); // 2023年5月15日 12:00:00
// 设置分钟
date.setMinutes(30);
console.log(date); // 2023年5月15日 12:30:00
// 设置秒数
date.setSeconds(45);
console.log(date); // 2023年5月15日 12:30:45
// 设置毫秒
date.setMilliseconds(500);
console.log(date); // 2023年5月15日 12:30:45.500
设置时间戳
const date = new Date();
// 设置为特定时间戳
date.setTime(1684123825000);
console.log(date); // 对应时间戳的日期
设置UTC时间
const date = new Date();
// 设置UTC年份
date.setUTCFullYear(2023);
// 设置UTC月份
date.setUTCMonth(4); // 5月
// 设置UTC日期
date.setUTCDate(15);
// 设置UTC小时
date.setUTCHours(6); // UTC时间6点
console.log(date); // 本地时间显示(取决于您的时区)
日期计算
日期加减
const date = new Date(2023, 4, 15);
// 加一天
date.setDate(date.getDate() + 1);
console.log(date); // 2023年5月16日
// 减一周
date.setDate(date.getDate() - 7);
console.log(date); // 2023年5月9日
// 加一个月
date.setMonth(date.getMonth() + 1);
console.log(date); // 2023年6月9日
// 加一年
date.setFullYear(date.getFullYear() + 1);
console.log(date); // 2024年6月9日
计算时间差
const date1 = new Date(2023, 0, 1); // 2023年1月1日
const date2 = new Date(2023, 11, 31); // 2023年12月31日
// 计算两个日期之间的毫秒数
const diffMs = date2.getTime() - date1.getTime();
console.log(diffMs); // 毫秒数
// 转换为天数
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
console.log(diffDays); // 364天
// 计算两个日期之间的月数(近似值)
const diffMonths = (date2.getFullYear() - date1.getFullYear()) * 12 +
(date2.getMonth() - date1.getMonth());
console.log(diffMonths); // 11个月
日期格式化
内置格式化方法
const date = new Date(2023, 4, 15, 14, 30, 25);
// 转换为字符串
console.log(date.toString());
// "Mon May 15 2023 14:30:25 GMT+0800 (中国标准时间)"
// 转换为本地日期字符串
console.log(date.toLocaleDateString());
// "2023/5/15"(格式因地区而异)
// 转换为本地时间字符串
console.log(date.toLocaleTimeString());
// "14:30:25"(格式因地区而异)
// 转换为本地日期和时间字符串
console.log(date.toLocaleString());
// "2023/5/15 14:30:25"(格式因地区而异)
// ISO格式
console.log(date.toISOString());
// "2023-05-15T06:30:25.000Z"(UTC时间)
// UTC字符串
console.log(date.toUTCString());
// "Mon, 15 May 2023 06:30:25 GMT"
使用Intl.DateTimeFormat进行本地化格式化
const date = new Date(2023, 4, 15, 14, 30, 25);
// 基本用法
const formatter = new Intl.DateTimeFormat('zh-CN');
console.log(formatter.format(date)); // "2023/5/15"
// 自定义格式
const options = {
year: 'numeric',
month: 'long',
day: 'numeric',
weekday: 'long',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZoneName: 'short'
};
const detailedFormatter = new Intl.DateTimeFormat('zh-CN', options);
console.log(detailedFormatter.format(date));
// "2023年5月15日星期一 14:30:25 GMT+8"
// 不同地区的格式
console.log(new Intl.DateTimeFormat('en-US').format(date)); // "5/15/2023"
console.log(new Intl.DateTimeFormat('de-DE').format(date)); // "15.5.2023"
console.log(new Intl.DateTimeFormat('ja-JP').format(date)); // "2023/5/15"
自定义格式化函数
// 简单的日期格式化函数
function formatDate(date, format) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return format
.replace('YYYY', year)
.replace('MM', month)
.replace('DD', day)
.replace('HH', hours)
.replace('mm', minutes)
.replace('ss', seconds);
}
const date = new Date(2023, 4, 15, 14, 30, 25);
console.log(formatDate(date, 'YYYY-MM-DD')); // "2023-05-15"
console.log(formatDate(date, 'YYYY年MM月DD日 HH:mm:ss')); // "2023年05月15日 14:30:25"
解析日期字符串
使用Date构造函数
// 解析ISO格式的日期字符串
const date1 = new Date('2023-05-15T14:30:25');
console.log(date1);
// 解析简单日期字符串
const date2 = new Date('2023-05-15');
console.log(date2);
// 解析其他格式(可能因浏览器而异)
const date3 = new Date('May 15, 2023 14:30:25');
console.log(date3);
使用Date.parse()
// 解析日期字符串,返回时间戳
const timestamp = Date.parse('2023-05-15T14:30:25');
console.log(timestamp); // 毫秒数
// 使用时间戳创建Date对象
const date = new Date(timestamp);
console.log(date);
常见问题和注意事项
1. 月份从0开始
// 创建2023年1月1日的日期
const date = new Date(2023, 0, 1); // 月份是0(一月)
console.log(date); // 2023年1月1日
2. 日期溢出会自动调整
// 使用超出范围的日期
const date = new Date(2023, 1, 31); // 2月31日不存在
console.log(date); // 自动调整为2023年3月3日(在非闰年)
3. 时区问题
const date = new Date(2023, 4, 15, 12, 0, 0);
// 本地时间
console.log(date.toString()); // 包含时区信息
// UTC时间
console.log(date.toUTCString()); // UTC时间
// 获取时区偏移(分钟)
console.log(date.getTimezoneOffset()); // 例如:-480(表示UTC+8)
4. 日期比较
const date1 = new Date(2023, 0, 1);
const date2 = new Date(2023, 11, 31);
// 比较两个日期
console.log(date1 < date2); // true
console.log(date1 > date2); // false
console.log(date1.getTime() === date2.getTime()); // false
// 检查日期是否相等(需要比较时间戳)
function areDatesEqual(date1, date2) {
return date1.getTime() === date2.getTime();
}
const date3 = new Date(2023, 0, 1);
console.log(areDatesEqual(date1, date3)); // true
5. 无效日期
// 创建无效日期
const invalidDate = new Date('not a date');
console.log(invalidDate); // Invalid Date
// 检查日期是否有效
function isValidDate(date) {
return !isNaN(date.getTime());
}
console.log(isValidDate(new Date())); // true
console.log(isValidDate(invalidDate)); // false
实际应用示例
1. 日期选择器
// 生成日期选择器的年、月、日选项
function generateDateOptions() {
const today = new Date();
const currentYear = today.getFullYear();
// 生成年份选项(前后10年)
const years = [];
for (let i = currentYear - 10; i <= currentYear + 10; i++) {
years.push(i);
}
// 生成月份选项
const months = [];
for (let i = 0; i < 12; i++) {
const date = new Date(2000, i, 1);
months.push({
value: i,
name: date.toLocaleString('zh-CN', { month: 'long' })
});
}
// 生成当月天数选项
function getDaysInMonth(year, month) {
const days = [];
const daysCount = new Date(year, month + 1, 0).getDate();
for (let i = 1; i <= daysCount; i++) {
days.push(i);
}
return days;
}
return {
years,
months,
getDaysInMonth
};
}
const dateOptions = generateDateOptions();
console.log(dateOptions.years); // 年份数组
console.log(dateOptions.months); // 月份对象数组
console.log(dateOptions.getDaysInMonth(2023, 1)); // 2023年2月的天数数组
2. 倒计时计算器
// 计算两个日期之间的倒计时
function calculateCountdown(targetDate) {
const now = new Date();
const difference = targetDate.getTime() - now.getTime();
// 如果目标日期已过,返回全零
if (difference <= 0) {
return { days: 0, hours: 0, minutes: 0, seconds: 0 };
}
// 计算天、时、分、秒
const days = Math.floor(difference / (1000 * 60 * 60 * 24));
const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((difference % (1000 * 60)) / 1000);
return { days, hours, minutes, seconds };
}
// 示例:计算到2024年新年的倒计时
const newYear = new Date(2024, 0, 1);
console.log(calculateCountdown(newYear));
// 输出类似:{ days: 245, hours: 9, minutes: 30, seconds: 15 }
// 实时倒计时(每秒更新一次)
function startCountdown(targetDate, callback) {
const timer = setInterval(() => {
const countdown = calculateCountdown(targetDate);
// 如果倒计时结束,清除定时器
if (countdown.days === 0 && countdown.hours === 0 &&
countdown.minutes === 0 && countdown.seconds === 0) {
clearInterval(timer);
}
callback(countdown);
}, 1000);
return timer; // 返回定时器ID,以便可以停止倒计时
}
// 使用示例
// startCountdown(newYear, (countdown) => {
// console.log(`${countdown.days}天 ${countdown.hours}时 ${countdown.minutes}分 ${countdown.seconds}秒`);
// });
3. 日程安排
// 简单的日程管理
class Calendar {
constructor() {
this.events = [];
}
// 添加事件
addEvent(title, startDate, endDate = null) {
if (!endDate) {
endDate = new Date(startDate.getTime());
endDate.setHours(startDate.getHours() + 1); // 默认持续1小时
}
this.events.push({ title, startDate, endDate });
return this.events.length - 1; // 返回事件索引
}
// 获取特定日期的事件
getEventsOnDate(date) {
const targetDate = new Date(date);
targetDate.setHours(0, 0, 0, 0); // 设置为当天开始时间
const nextDay = new Date(targetDate);
nextDay.setDate(nextDay.getDate() + 1); // 下一天
return this.events.filter(event => {
return event.startDate >= targetDate && event.startDate < nextDay;
});
}
// 获取两个日期之间的事件
getEventsBetweenDates(startDate, endDate) {
return this.events.filter(event => {
return event.startDate >= startDate && event.startDate <= endDate;
});
}
// 删除事件
removeEvent(index) {
if (index >= 0 && index < this.events.length) {
this.events.splice(index, 1);
return true;
}
return false;
}
}
// 使用示例
const myCalendar = new Calendar();
// 添加事件
const eventIndex = myCalendar.addEvent(
'团队会议',
new Date(2023, 4, 15, 14, 0), // 2023年5月15日 14:00
new Date(2023, 4, 15, 15, 30) // 2023年5月15日 15:30
);
// 获取特定日期的事件
const eventsToday = myCalendar.getEventsOnDate(new Date(2023, 4, 15));
console.log(eventsToday); // 包含"团队会议"事件
// 删除事件
myCalendar.removeEvent(eventIndex);
4. 年龄计算器
// 计算年龄
function calculateAge(birthDate) {
const today = new Date();
const birth = new Date(birthDate);
let age = today.getFullYear() - birth.getFullYear();
const monthDifference = today.getMonth() - birth.getMonth();
// 如果今年的生日还没到,减去一岁
if (monthDifference < 0 || (monthDifference === 0 && today.getDate() < birth.getDate())) {
age--;
}
return age;
}
console.log(calculateAge('1990-05-15')); // 根据当前日期计算年龄
// 更详细的年龄计算
function calculateDetailedAge(birthDate) {
const today = new Date();
const birth = new Date(birthDate);
let years = today.getFullYear() - birth.getFullYear();
let months = today.getMonth() - birth.getMonth();
let days = today.getDate() - birth.getDate();
// 调整月份和天数
if (days < 0) {
months--;
// 获取上个月的天数
const lastMonth = new Date(today.getFullYear(), today.getMonth(), 0);
days += lastMonth.getDate();
}
if (months < 0) {
years--;
months += 12;
}
return { years, months, days };
}
console.log(calculateDetailedAge('1990-05-15'));
// 输出类似:{ years: 33, months: 0, days: 0 }(如果今天是2023年5月15日)
总结
JavaScript的Date对象提供了丰富的功能来处理日期和时间:
创建日期:可以通过多种方式创建Date对象,包括当前时间、指定时间戳、日期字符串或年月日值。
获取和设置:Date对象提供了方法来获取和设置日期时间的各个部分,如年、月、日、时、分、秒等。
日期计算:可以进行日期加减、计算时间差等操作。
格式化:可以使用内置方法或Intl.DateTimeFormat进行日期格式化,也可以编写自定义格式化函数。
解析:可以解析各种格式的日期字符串。
在使用Date对象时,需要注意月份从0开始、日期溢出自动调整、时区问题等特性。通过合理使用Date对象,可以实现日期选择器、倒计时计算器、日程安排和年龄计算等实际应用。
练习
编写一个函数,计算给定日期是一年中的第几天。
实现一个函数,判断给定年份是否为闰年。
创建一个日期格式化函数,支持多种格式模板(如"YYYY-MM-DD"、"DD/MM/YYYY"等)。
编写一个函数,计算两个日期之间的工作日天数(不包括周六和周日)。
实现一个简单的日历组件,显示指定月份的日历视图。