返回
《JavaScript高级程序设计(第3版)》读书笔记5:深入探索Date对象
前端
2023-12-18 04:23:18
# 《JavaScript高级程序设计(第3版)》读书笔记5:深入探索Date对象
## 1. Date对象
Date对象是JavaScript中的内置对象,用于表示日期和时间。它可以通过new操作符或Date构造函数来创建。
```javascript
// 使用new操作符创建Date对象
const date1 = new Date();
// 使用Date构造函数创建Date对象
const date2 = new Date(2023, 3, 8, 12, 30, 0);
Date对象提供了许多方法来获取和设置日期和时间信息,以及解析日期字符串、比较日期、格式化日期和时间等功能。
2. 获取和设置日期和时间信息
Date对象提供了以下方法来获取和设置日期和时间信息:
Date.parse()
:接收一个表示日期的字符串参数,返回相应日期的毫秒数。Date.UTC()
:接收年、月、日、时、分、秒和毫秒参数,返回相应日期和时间的毫秒数。Date.now()
:返回当前时间戳,即自1970年1月1日午夜以来的毫秒数。Date.prototype.toString()
:返回一个字符串,表示日期和时间。Date.prototype.toDateString()
:返回一个字符串,表示日期。Date.prototype.toLocaleString()
:返回一个字符串,表示日期和时间,并使用本地化格式。Date.prototype.toLocaleDateString()
:返回一个字符串,表示日期,并使用本地化格式。Date.prototype.toLocaleTimeString()
:返回一个字符串,表示时间,并使用本地化格式。Date.prototype.getTimezoneOffset()
:返回与UTC时间的时差,以分钟为单位。Date.prototype.setFullYear()
:设置年份。Date.prototype.setMonth()
:设置月份。Date.prototype.setDate()
:设置日期。Date.prototype.setHours()
:设置小时。Date.prototype.setMinutes()
:设置分钟。Date.prototype.setSeconds()
:设置秒。Date.prototype.setMilliseconds()
:设置毫秒。Date.prototype.getFullYear()
:获取年份。Date.prototype.getMonth()
:获取月份。Date.prototype.getDate()
:获取日期。Date.prototype.getHours()
:获取小时。Date.prototype.getMinutes()
:获取分钟。Date.prototype.getSeconds()
:获取秒。Date.prototype.getMilliseconds()
:获取毫秒。Date.prototype.valueOf()
:返回日期和时间的毫秒数。
3. 解析日期字符串
Date对象提供了Date.parse()
方法来解析日期字符串。该方法接收一个表示日期的字符串参数,返回相应日期的毫秒数。
const dateString = "2023-03-08T12:30:00.000Z";
const date = Date.parse(dateString);
console.log(date); // 1678262200000
4. 比较日期
Date对象提供了以下方法来比较日期:
>
:大于。<
:小于。>=
:大于等于。<=
:小于等于。==
:等于。!=
:不等于。
const date1 = new Date("2023-03-08");
const date2 = new Date("2023-03-09");
console.log(date1 > date2); // false
console.log(date1 < date2); // true
console.log(date1 >= date2); // false
console.log(date1 <= date2); // true
console.log(date1 == date2); // false
console.log(date1 != date2); // true
5. 格式化日期和时间
Date对象提供了以下方法来格式化日期和时间:
Date.prototype.toString()
:返回一个字符串,表示日期和时间。Date.prototype.toDateString()
:返回一个字符串,表示日期。Date.prototype.toLocaleString()
:返回一个字符串,表示日期和时间,并使用本地化格式。Date.prototype.toLocaleDateString()
:返回一个字符串,表示日期,并使用本地化格式。Date.prototype.toLocaleTimeString()
:返回一个字符串,表示时间,并使用本地化格式。
const date = new Date();
console.log(date.toString()); // "Wed Mar 08 2023 12:30:00 GMT+0800 (中国标准时间)"
console.log(date.toDateString()); // "Wed Mar 08 2023"
console.log(date.toLocaleString()); // "2023/3/8 上午12:30:00"
console.log(date.toLocaleDateString()); // "2023/3/8"
console.log(date.toLocaleTimeString()); // "上午12:30:00"
结语
Date对象是JavaScript中一个非常重要的对象,它提供了许多方法来处理日期和时间。这些方法可以帮助我们轻松地创建、获取、设置、解析、比较和格式化日期和时间。
通过本文的学习,我们对Date对象及其相关方法有了更深入的理解。这将使我们能够在开发中更有效地处理日期和时间相关的数据和逻辑。