JS 函数--Date()函数

Date() 是 JavaScript 中的内置函数,用于创建一个表示日期和时间的对象。它可以获取当前的日期和时间,也可以指定特定的日期和时间。

使用方法:

1. 创建 Date 对象:

- 不传参数:`var currentDate = new Date();`,这将创建一个表示当前日期和时间的对象。

- 传递日期字符串:`var specificDate = new Date("2021-09-01");`,这将创建一个表示指定日期的对象。日期字符串的格式可以是 "YYYY-MM-DD" 或 "MM/DD/YYYY"。

- 传递年、月、日等参数:`var specificDate = new Date(2021, 8, 1);`,这将创建一个表示指定年、月、日的对象。月份从 0 开始计数,所以 8 表示 9 月。

2. 获取日期和时间的信息:

- 年份:`var year = currentDate.getFullYear();`

- 月份:`var month = currentDate.getMonth();`,返回值为 0-11,需要加 1 才是实际的月份。

- 日期:`var day = currentDate.getDate();`

- 小时:`var hour = currentDate.getHours();`

- 分钟:`var minutes = currentDate.getMinutes();`

- 秒钟:`var seconds = currentDate.getSeconds();`

- 毫秒:`var milliseconds = currentDate.getMilliseconds();`

3. 设置日期和时间的信息:

- 年份:`currentDate.setFullYear(2022);`

- 月份:`currentDate.setMonth(9);`,传入的值为 0-11 的范围。

- 日期:`currentDate.setDate(15);`

- 小时:`currentDate.setHours(10);`

- 分钟:`currentDate.setMinutes(30);`

- 秒钟:`currentDate.setSeconds(45);`

- 毫秒:`currentDate.setMilliseconds(123);`

4. 格式化日期和时间:

- 将日期转换为字符串:

- `currentDate.toString()`:返回带有日期和时间的字符串,格式为 "Dow Mon DD YYYY HH:MM:SS GMT+hhmm (TZ)"。

- `currentDate.toDateString()`:返回带有日期的字符串,格式为 "Mon DD YYYY"。

- `currentDate.toISOString()`:返回符合 ISO 8601 格式的日期字符串。

- `currentDate.toLocaleDateString()`:返回带有本地日期的字符串。

- 将时间转换为字符串:

- `currentDate.toTimeString()`:返回带有时间的字符串,格式为 "HH:MM:SS GMT+hhmm (TZ)"。

- `currentDate.toLocaleTimeString()`:返回带有本地时间的字符串。

- `currentDate.toISOString()`:返回符合 ISO 8601 格式的时间字符串。

案例说明:

```javascript

// 获取当前日期和时间

var currentDate = new Date();

console.log(currentDate); // 输出当前日期和时间的对象

// 获取年份和月份

var year = currentDate.getFullYear();

var month = currentDate.getMonth() + 1;

console.log(year + "-" + month); // 输出当前年份和月份,例如:2021-9

// 设置日期为指定日期

currentDate.setDate(15);

console.log(currentDate); // 输出日期被设置为15号后的日期和时间的对象

// 格式化日期字符串

console.log(currentDate.toDateString()); // 输出格式为 "Mon DD YYYY" 的日期字符串

console.log(currentDate.toISOString()); // 输出符合 ISO 8601 格式的日期字符串

```

总结:

Date() 函数是 JavaScript 中用于处理日期和时间的内置函数。通过 Date() 函数,我们可以创建表示日期和时间的对象,获取和设置日期和时间的信息,以及格式化日期和时间的字符串。这些功能可以帮助我们在 JavaScript 中轻松地处理日期和时间。 如果你喜欢我们三七知识分享网站的文章, 欢迎您分享或收藏知识分享网站文章 欢迎您到我们的网站逛逛喔!https://www.37seo.cn/

点赞(117) 打赏

评论列表 共有 1 条评论

天风海涛 1年前 回复TA

我不敢买彩票什么的,怕花光遇见你的好运。

立即
投稿
发表
评论
返回
顶部