在 JavaScript 中获取日期的全面指南185


获取日期是 JavaScript 中一个常见的任务。有几种不同的方法可以获取日期,本文将介绍每种方法并提供代码示例。## 使用 Date 构造函数

创建 Date 对象的最简单方法是使用 Date 构造函数。此构造函数会创建一个表示当前日期和时间的对象。```javascript
const date = new Date();
(date);
```

输出:```
Tue Apr 19 2022 16:12:35 GMT-0400 (Eastern Daylight Time)
```
## 使用 ()

() 方法返回自纪元时间(即 1970 年 1 月 1 日午夜 UTC)以来经过的毫秒数。```javascript
const timestamp = ();
(timestamp);
```

输出:```
1650416355676
```
## 使用 ()

() 方法解析字符串表示的日期并返回自纪元时间以来经过的毫秒数。```javascript
const dateString = "April 19, 2022";
const timestamp = (dateString);
(timestamp);
```

输出:```
1650412800000
```
## 使用 getFullYear()

getFullYear() 方法返回 Date 对象的年份。```javascript
const date = new Date();
const year = ();
(year);
```

输出:```
2022
```
## 使用 getMonth()

getMonth() 方法返回 Date 对象的月份(从 0 到 11)。```javascript
const date = new Date();
const month = ();
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
(monthNames[month]);
```

输出:```
April
```
## 使用 getDate()

getDate() 方法返回 Date 对象的日期(从 1 到 31)。```javascript
const date = new Date();
const day = ();
(day);
```

输出:```
19
```
## 使用 getHours()

getHours() 方法返回 Date 对象的小时(从 0 到 23)。```javascript
const date = new Date();
const hours = ();
(hours);
```

输出:```
16
```
## 使用 getMinutes()

getMinutes() 方法返回 Date 对象的分钟(从 0 到 59)。```javascript
const date = new Date();
const minutes = ();
(minutes);
```

输出:```
12
```
## 使用 getSeconds()

getSeconds() 方法返回 Date 对象的秒数(从 0 到 59)。```javascript
const date = new Date();
const seconds = ();
(seconds);
```

输出:```
35
```
## 使用 getMilliseconds()

getMilliseconds() 方法返回 Date 对象的毫秒(从 0 到 999)。```javascript
const date = new Date();
const milliseconds = ();
(milliseconds);
```

输出:```
676
```
## 使用 toDateString()

toDateString() 方法返回 Date 对象的本地日期字符串。```javascript
const date = new Date();
const dateString = ();
(dateString);
```

输出:```
Tue Apr 19 2022
```
## 使用 toTimeString()

toTimeString() 方法返回 Date 对象的本地时间字符串。```javascript
const date = new Date();
const timeString = ();
(timeString);
```

输出:```
16:12:35 GMT-0400 (Eastern Daylight Time)
```
## 使用 toLocaleDateString()

toLocaleDateString() 方法返回 Date 对象的本地日期字符串(根据浏览器设置的语言环境)。```javascript
const date = new Date();
const dateString = ();
(dateString);
```

输出:```
4/19/2022
```
## 使用 toLocaleTimeString()

toLocaleTimeString() 方法返回 Date 对象的本地时间字符串(根据浏览器设置的语言环境)。```javascript
const date = new Date();
const timeString = ();
(timeString);
```

输出:```
4:12:35 PM
```
## 使用 ()

() 构造函数可用于创建日期和时间格式化程序。它提供了一种更灵活的方法来格式化日期和时间。```javascript
const date = new Date();
const options = { year: 'numeric', month: 'long', day: 'numeric' };
const dateFormatter = new ('en-US', options);
const dateString = (date);
(dateString);
```

输出:```
April 19, 2022
```

2024-12-02


上一篇:从头到尾搞定 JavaScript 文件下载

下一篇:JavaScript 与 Python:全方位比较