JavaScript Date(日期) 对象
                           
天天向上
发布: 2025-03-01 00:02:00

原创
20 人浏览过

在 JavaScript 中,Date 对象用于处理和操作日期与时间。它可以获取当前日期和时间,进行日期的计算,格式化输出日期等。Date 对象既可以用来处理当前日期,也可以用来创建和操作任意的时间点。

1. 创建 Date 对象

1.1 获取当前日期和时间

直接调用 new Date() 不传入任何参数时,返回当前的日期和时间。

const now = new Date();
console.log(now);  // 输出当前日期和时间,格式类似:Mon Feb 28 2025 12:34:56 GMT+0000 (UTC)

1.2 指定日期和时间

你可以通过传递不同的参数来创建指定的日期和时间:

  • new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds) 其中,monthIndex 是从 0 开始的,即 0 代表一月,1 代表二月,以此类推。
// 创建 2025 年 2 月 28 日 12:34:56 的日期
const specificDate = new Date(2025, 1, 28, 12, 34, 56);
console.log(specificDate);  // 输出:Fri Feb 28 2025 12:34:56 GMT+0000 (UTC)

1.3 通过字符串创建日期

你还可以通过传递一个日期字符串(ISO 8601 格式或常见的日期格式)来创建 Date 对象。

const dateString = new Date("2025-02-28T12:34:56Z");
console.log(dateString);  // 输出:Fri Feb 28 2025 12:34:56 GMT+0000 (UTC)

1.4 通过时间戳创建日期

Date 还可以通过毫秒级别的时间戳来创建。时间戳表示自 1970 年 1 月 1 日 00:00:00 UTC 到指定时间的毫秒数。

const timestampDate = new Date(1700000000000);  // 时间戳示例
console.log(timestampDate);  // 输出:Sun Dec 01 2024 03:46:40 GMT+0000 (UTC)

2. 获取日期和时间

一旦创建了 Date 对象,可以使用多种方法获取日期和时间的各个部分。

2.1 获取当前日期和时间的各个部分

  • getFullYear():获取年份。
  • getMonth():获取月份(0-11,0表示一月)。
  • getDate():获取月份中的日期(1-31)。
  • getDay():获取星期几(0-6,0表示星期天)。
  • getHours():获取小时(0-23)。
  • getMinutes():获取分钟(0-59)。
  • getSeconds():获取秒数(0-59)。
  • getMilliseconds():获取毫秒(0-999)。
  • getTime():获取从1970年1月1日00:00:00 UTC 到当前时间的毫秒数。
  • getTimezoneOffset():获取当前时区相对于 UTC 的偏移量(单位为分钟,西方偏移为正值,东方偏移为负值)。
const now = new Date();
console.log(now.getFullYear());         // 2025
console.log(now.getMonth());            // 1 (2月)
console.log(now.getDate());             // 28
console.log(now.getDay());              // 5 (星期五)
console.log(now.getHours());            // 12 (时)
console.log(now.getMinutes());          // 34 (分)
console.log(now.getSeconds());          // 56 (秒)
console.log(now.getMilliseconds());     // 789 (毫秒)
console.log(now.getTime());             // 1677482096789 (时间戳)
console.log(now.getTimezoneOffset());   // 0(UTC时区偏移)

2.2 获取 UTC 时间

如果你需要获取 UTC 时间(协调世界时),可以使用与 get 方法对应的 getUTC 方法。

console.log(now.getUTCFullYear());        // 2025
console.log(now.getUTCMonth());           // 1 (2月)
console.log(now.getUTCDate());            // 28
console.log(now.getUTCDay());             // 5 (星期五)
console.log(now.getUTCHours());           // 12
console.log(now.getUTCMinutes());         // 34
console.log(now.getUTCSeconds());         // 56
console.log(now.getUTCMilliseconds());    // 789

3. 修改日期和时间

你可以使用 set 方法来修改 Date 对象的各个部分。

  • setFullYear(year, monthIndex, day):设置年份、月份和日期。
  • setMonth(monthIndex, day):设置月份和日期。
  • setDate(day):设置日期(1-31)。
  • setHours(hours, minutes, seconds, milliseconds):设置小时、分钟、秒和毫秒。
  • setMinutes(minutes, seconds, milliseconds):设置分钟、秒和毫秒。
  • setSeconds(seconds, milliseconds):设置秒和毫秒。
  • setMilliseconds(milliseconds):设置毫秒。
  • setTime(milliseconds):通过时间戳设置日期。

示例:修改日期

const date = new Date(2025, 1, 28, 12, 34, 56); // 2025-02-28 12:34:56
date.setFullYear(2026);
date.setMonth(0);  // 1月
date.setDate(15);   // 15号

console.log(date);  // 输出:Thu Jan 15 2026 12:34:56 GMT+0000 (UTC)

4. 日期比较

你可以直接使用 Date 对象进行日期比较,因为 Date 对象会自动调用其 valueOf() 方法返回时间戳。

const date1 = new Date(2025, 1, 28);
const date2 = new Date(2025, 1, 28);

console.log(date1 === date2);  // false,因为它们是不同的对象
console.log(date1.getTime() === date2.getTime());  // true,因为它们的时间戳相同

5. 日期格式化

JavaScript 中没有内建的日期格式化方法,但可以使用 toLocaleDateString()toLocaleTimeString() 方法以不同的格式输出日期和时间。

  • toLocaleDateString(locales, options):根据语言环境输出日期。
  • toLocaleTimeString(locales, options):根据语言环境输出时间。
  • toLocaleString(locales, options):同时输出日期和时间。
const now = new Date();

// 默认格式(根据系统语言)
console.log(now.toLocaleDateString());   // 2025/2/28
console.log(now.toLocaleTimeString());   // 12:34:56

// 自定义格式
const options = { year: 'numeric', month: 'long', day: 'numeric' };
console.log(now.toLocaleDateString('en-US', options));  // February 28, 2025
console.log(now.toLocaleDateString('zh-CN', options));  // 2025年2月28日

// 输出日期和时间
console.log(now.toLocaleString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }));
// Thursday, February 28, 2025

6. 实战案例:日期计算

假设你想计算两个日期之间的差异(例如,计算两个日期之间的天数)。

function calculateDaysBetweenDates(date1, date2) {
  const msInDay = 1000 * 60 * 60 * 24; // 每天的毫秒数
  const diffInMs = Math.abs(date2 - date1); // 计算两个日期的差异(毫秒)
  return Math.floor(diffInMs / msInDay);    // 将毫秒转为天数
}

const date1 = new Date(2025, 1, 28); // 2025-02-28
const date2 = new Date(2025, 2, 5);  // 2025-03-05

console.log(calculateDaysBetweenDates(date1, date2));  // 输出:5

7. 总结

Date 对象是 JavaScript 中非常重要的对象,用于处理日期和时间的计算、格式化以及各种操作。通过 Date 的各种方法,你可以轻松获取当前日期、时间,修改日期,进行日期的比较和格式化等。

更多详细内容请关注其他相关文章!

发表回复 0

Your email address will not be published. Required fields are marked *