replace 日期格式转换
时间: 2023-11-07 20:01:51 浏览: 38
replace函数可以用于日期格式转换,通过替换模板中的占位符来生成所需格式的日期字符串。在给定的引用中,有两种方法可以使用replace函数进行日期格式转换。
第一种方法是通过原型对象打点方式,即使用String.prototype来添加一个名为formatTime的方法,并在该方法内部使用replace函数进行替换。该方法的代码如下所示:
```javascript
String.prototype.formatTime = function formatTime(template) {
// 初始化模板
typeof template === 'undefined' ? template = '{0}年{1}月{2}日 {3}:{4}:{5}' : null;
// 获取日期字符串中的数字信息
let matchAry = this.match(/\d+/g);
// 模板和数字的渲染
template = template.replace(/\{(\d+)\}/g, (x, y) => {
let val = matchAry[y] || '00';
val.length < 2 ? val = '0' + val : val;
return val;
});
return template;
}
console.log('2021-03-03 13:26:23'.formatTime('{0}/{1}/{2} {3}'));
```
第二种方法是通过函数传参方式,即将日期字符串和模板作为函数的参数,并在函数内部使用replace函数进行替换。该方法的代码如下所示:
```javascript
function formatTime(time, template) {
// 初始化模板
typeof template === 'undefined' ? template = '{0}年{1}月{2}日 {3}:{4}:{5}' : null;
// 获取日期字符串中的数字信息
let matchAry = time.match(/\d+/g);
// 模板和数字的渲染
template = template.replace(/\{(\d+)\}/g, (x, y) => {
let val = matchAry[y] || '00';
val.length < 2 ? val = '0' + val : val;
return val;
});
return template;
}
console.log(formatTime('2021-03-03 13:26:23', '{0}-{1}-{2} {3}:{4}'));
```
这两种方法都使用replace函数,通过匹配模板中的占位符,将日期字符串中的数字信息进行替换,从而生成所需格式的日期字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)