js用日期时间字符串获取小时
时间: 2024-04-29 14:27:12 浏览: 21
的两种方法是什么?
可以使用 JavaScript Date 对象的 getHours() 方法获取时间字符串的小时部分,也可以使用正则表达式对时间字符串进行匹配提取小时部分。以下是两种方法的示例代码:
方法一:使用 Date 对象的 getHours() 方法
```javascript
const dateString = '2022-01-01 12:34:56';
const date = new Date(dateString);
const hour = date.getHours();
console.log(hour); // 输出 12
```
方法二:使用正则表达式匹配提取小时部分
```javascript
const dateString = '2022-01-01 12:34:56';
const hourRegex = /\b(\d{2}):/;
const match = hourRegex.exec(dateString);
const hour = match[1];
console.log(hour); // 输出 12
```
相关问题
js 获取当前日期字符串
要获取当前日期字符串,你可以使用 JavaScript 中的 Date 对象和相应的方法。以下是获取当前日期字符串的一种常见方式:
```javascript
const currentDate = new Date();
const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, '0');
const day = String(currentDate.getDate()).padStart(2, '0');
const dateString = `${year}-${month}-${day}`;
console.log(dateString);
```
这段代码将获取当前日期,并将其格式化为 'YYYY-MM-DD' 的字符串。例如,如果今天是2022年9月15日,则输出结果为 '2022-09-15'。你可以根据需要自定义日期字符串的格式。
js moment对象获取时间字符串
以下是使用moment对象获取时间字符串的例子:
```javascript
const momentObj = moment();
const timeString = momentObj.format('YYYY-MM-DD HH:mm:ss');
console.log(timeString); // 输出当前时间的字符串形式,例如:2022-01-01 12:00:00
```
以上代码中,我们首先使用moment()函数创建了一个moment对象,然后使用format()函数将其转换为字符串形式。format()函数的参数是一个格式化字符串,其中YYYY表示年份,MM表示月份,DD表示日期,HH表示小时,mm表示分钟,ss表示秒钟。你可以根据自己的需要自定义格式化字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)