使用 JavaScript Date 对象操作日期

CSSBeginner
立即练习

介绍

在本实验中,你将探索强大的 JavaScript Date 对象,并学习操作日期和时间的基本技巧。通过全面的实践方法,你将了解如何使用各种初始化方法创建 Date 对象、获取特定的日期组件、格式化和显示日期信息、使用 setter 方法修改日期,以及执行复杂的日期计算。

本实验提供了关于在 JavaScript 中处理日期的实用、逐步指导,涵盖了从当前时间、特定时间戳、日期字符串和 Unix 纪元以来的毫秒数创建 Date 对象的基本技能。通过本实验的学习,你将掌握日期操作技巧,从而能够在 JavaScript 应用程序中有效地处理与日期相关的任务。

创建一个新的 Date 对象

在这一步中,你将学习如何在 JavaScript 中创建新的 Date 对象,这是处理日期和时间的基础。JavaScript 的 Date 对象使你可以轻松地处理日期和时间。

首先,打开 WebIDE 并在 ~/project 目录下创建一个名为 dates.js 的新 JavaScript 文件。

使用不同的初始化方法创建一个新的 Date 对象:

// 创建一个表示当前日期和时间的 Date 对象
let currentDate = new Date();
console.log("Current Date:", currentDate);

// 创建一个具有特定日期和时间的 Date 对象
let specificDate = new Date(2023, 5, 15, 10, 30, 0);
console.log("Specific Date:", specificDate);

// 从日期字符串创建一个 Date 对象
let stringDate = new Date("2023-06-15");
console.log("Date from String:", stringDate);

// 使用自 Unix 纪元以来的毫秒数创建一个 Date 对象
let millisecondDate = new Date(1686816000000);
console.log("Date from Milliseconds:", millisecondDate);

示例输出:

Current Date: Thu Jun 15 2023 12:00:00 GMT+0000 (Coordinated Universal Time)
Specific Date: Thu Jun 15 2023 10:30:00 GMT+0000 (Coordinated Universal Time)
Date from String: Thu Jun 15 2023 00:00:00 GMT+0000 (Coordinated Universal Time)
Date from Milliseconds: Thu Jun 15 2023 00:00:00 GMT+0000 (Coordinated Universal Time)

需要记住的关键点:

  • new Date() 创建一个包含当前日期和时间的 Date 对象
  • new Date(year, month, day, hours, minutes, seconds) 允许创建一个特定的日期
  • 月份是从零开始索引的(0-11),因此 6 月用 5 表示
  • 你可以从字符串或自 Unix 纪元(1970 年 1 月 1 日)以来的毫秒数创建日期

获取当前日期的组成部分

在这一步中,你将学习如何从 Date 对象中提取特定的组成部分。基于上一步的内容,我们将使用 dates.js 文件来演示获取日期和时间组成部分的各种方法。

打开 ~/project/dates.js 文件并添加以下代码:

// 创建一个当前日期对象
let currentDate = new Date();

// 获取单独的日期组成部分
let year = currentDate.getFullYear();
let month = currentDate.getMonth(); // 0-11 (0 = 一月)
let day = currentDate.getDate(); // 月份中的第几天
let hours = currentDate.getHours();
let minutes = currentDate.getMinutes();
let seconds = currentDate.getSeconds();
let milliseconds = currentDate.getMilliseconds();

// 显示单独的组成部分
console.log("Year:", year);
console.log("Month:", month + 1); // 加 1 以显示实际的月份数字
console.log("Day of Month:", day);
console.log("Hours:", hours);
console.log("Minutes:", minutes);
console.log("Seconds:", seconds);
console.log("Milliseconds:", milliseconds);

// 获取星期几
let dayOfWeek = currentDate.getDay(); // 0-6 (0 = 星期日)
console.log("Day of Week:", dayOfWeek);

// 获取时间戳(自 Unix 纪元以来的毫秒数)
let timestamp = currentDate.getTime();
console.log("Timestamp:", timestamp);

示例输出:

Year: 2023
Month: 6
Day of Month: 15
Hours: 12
Minutes: 30
Seconds: 45
Milliseconds: 123
Day of Week: 4
Timestamp: 1686816045123

需要记住的关键点:

  • getFullYear() 返回四位数的年份
  • getMonth() 返回 0-11,因此需要加 1 以显示实际的月份数字
  • getDate() 返回月份中的第几天(1-31)
  • getDay() 返回星期几(0-6)
  • getTime() 返回自 1970 年 1 月 1 日以来的毫秒数

格式化并显示日期信息

在这一步中,你将学习在 JavaScript 中格式化并显示日期信息的多种方法。打开 ~/project/dates.js 文件并添加以下代码,以探索不同的格式化技术:

// 创建一个当前日期对象
let currentDate = new Date();

// 方法 1: 使用 toLocaleDateString()
let localeDateString = currentDate.toLocaleDateString();
console.log("Local Date String:", localeDateString);

// 方法 2: 使用 toDateString()
let dateString = currentDate.toDateString();
console.log("Date String:", dateString);

// 方法 3: 使用 toLocaleString()
let localeString = currentDate.toLocaleString();
console.log("Locale String:", localeString);

// 方法 4: 自定义格式化
let customFormat =
  `${currentDate.getFullYear()}-` +
  `${(currentDate.getMonth() + 1).toString().padStart(2, "0")}-` +
  `${currentDate.getDate().toString().padStart(2, "0")}`;
console.log("Custom Format:", customFormat);

// 方法 5: 国际化 API
let options = {
  weekday: "long",
  year: "numeric",
  month: "long",
  day: "numeric"
};
let intlFormat = currentDate.toLocaleDateString("en-US", options);
console.log("Internationalized Format:", intlFormat);

示例输出:

Local Date String: 6/15/2023
Date String: Thu Jun 15 2023
Locale String: 6/15/2023, 12:30:45 PM
Custom Format: 2023-06-15
Internationalized Format: Thursday, June 15, 2023

需要记住的关键点:

  • toLocaleDateString() 提供本地化的日期表示
  • toDateString() 提供人类可读的日期字符串
  • toLocaleString() 包含日期和时间
  • 自定义格式化允许精确控制日期的显示
  • 国际化 API 提供高级的本地化选项

使用 Setter 方法修改日期

在这一步中,你将学习如何使用 JavaScript 的 Date setter 方法修改日期的组成部分。打开 ~/project/dates.js 文件并添加以下代码,以探索修改日期值的不同方法:

// 创建一个新的 Date 对象
let modifiableDate = new Date();
console.log("Original Date:", modifiableDate);

// 设置特定的年份
modifiableDate.setFullYear(2024);
console.log("After setting year:", modifiableDate);

// 设置月份(0-11,因此 5 表示 6 月)
modifiableDate.setMonth(5);
console.log("After setting month:", modifiableDate);

// 设置月份中的第几天
modifiableDate.setDate(15);
console.log("After setting day:", modifiableDate);

// 设置小时(0-23)
modifiableDate.setHours(14);
console.log("After setting hours:", modifiableDate);

// 设置分钟(0-59)
modifiableDate.setMinutes(30);
console.log("After setting minutes:", modifiableDate);

// 设置秒数(0-59)
modifiableDate.setSeconds(45);
console.log("After setting seconds:", modifiableDate);

// 链式调用 setter 方法
let customDate = new Date();
customDate.setFullYear(2025).setMonth(11).setDate(31);
console.log("Custom Date:", customDate);

示例输出:

Original Date: Thu Jun 15 2023 12:30:45 GMT+0000
After setting year: Thu Jun 15 2024 12:30:45 GMT+0000
After setting month: Thu Jun 15 2024 12:30:45 GMT+0000
After setting day: Sat Jun 15 2024 12:30:45 GMT+0000
After setting hours: Sat Jun 15 2024 14:30:45 GMT+0000
After setting minutes: Sat Jun 15 2024 14:30:45 GMT+0000
After setting seconds: Sat Jun 15 2024 14:30:45 GMT+0000
Custom Date: Wed Dec 31 2025 00:00:00 GMT+0000

需要记住的关键点:

  • Setter 方法允许精确修改日期的组成部分
  • 月份是从零开始索引的(0-11)
  • 小时使用 24 小时制(0-23)
  • Setter 方法会修改原始的 Date 对象
  • 你可以链式调用某些 setter 方法以方便操作

执行日期计算

在这一步中,你将学习如何使用 JavaScript 的 Date 方法执行各种日期计算。打开 ~/project/dates.js 文件并添加以下代码,以探索不同的日期操作技术:

// 创建用于计算的日期对象
let currentDate = new Date();
let futureDate = new Date(currentDate.getTime());

// 向日期添加天数
futureDate.setDate(currentDate.getDate() + 30);
console.log("Current Date:", currentDate);
console.log("30 Days from Now:", futureDate);

// 计算日期之间的差异
let differenceInMilliseconds = futureDate.getTime() - currentDate.getTime();
let differenceInDays = Math.floor(
  differenceInMilliseconds / (1000 * 60 * 60 * 24)
);
console.log("Days Between Dates:", differenceInDays);

// 计算年龄或经过的时间
let birthDate = new Date("1990-01-01");
let ageInMilliseconds = currentDate.getTime() - birthDate.getTime();
let ageInYears = Math.floor(ageInMilliseconds / (1000 * 60 * 60 * 24 * 365.25));
console.log("Calculated Age:", ageInYears);

// 查找当前月份的最后一天
let lastDayOfMonth = new Date(
  currentDate.getFullYear(),
  currentDate.getMonth() + 1,
  0
);
console.log("Last Day of Current Month:", lastDayOfMonth);

// 检查某年是否为闰年
function isLeapYear(year) {
  return new Date(year, 1, 29).getMonth() === 1;
}
console.log("Is 2024 a Leap Year?", isLeapYear(2024));

示例输出:

Current Date: Thu Jun 15 2023 12:30:45 GMT+0000
30 Days from Now: Sat Jul 15 2023 12:30:45 GMT+0000
Days Between Dates: 30
Calculated Age: 33
Last Day of Current Month: Wed Jun 30 2023 00:00:00 GMT+0000
Is 2024 a Leap Year? true

需要记住的关键点:

  • 使用 getTime() 获取毫秒数以进行计算
  • 通过适当除法将毫秒数转换为天数
  • 你可以使用 setDate() 添加或减去天数
  • 计算日期之间的年龄或时间差异
  • 通过测试 2 月 29 日来检查闰年

总结

在本实验中,参与者通过全面探索日期的创建、检索和操作技术,学习了如何使用 JavaScript 的 Date 对象来操作日期。实验涵盖了多种初始化 Date 对象的方法,包括创建表示当前时刻的日期、使用参数指定确切日期、从字符串解析日期以及从毫秒时间戳生成日期。

实践练习展示了关键的 JavaScript 日期处理技能,例如提取特定的日期组成部分、格式化日期信息、应用 setter 方法修改日期以及执行日期计算。参与者通过实际操作,掌握了零索引的月份表示方法,理解了不同的 Date 对象初始化策略,并利用 JavaScript 内置方法在各种编程场景中有效地处理时间数据。