生成js日期格式化工具类
时间: 2023-08-18 11:10:04 浏览: 59
下面是一个简单的 JavaScript 日期格式化工具类:
```javascript
/**
* 日期格式化工具类
*/
const DateFormatUtil = {
/**
* 格式化日期
* @param {Date} date 日期对象
* @param {string} format 格式化字符串
* @return {string} 格式化后的日期字符串
*/
formatDate: function(date, format) {
const o = {
"M+": date.getMonth() + 1, //月份
"d+": date.getDate(), //日
"h+": date.getHours(), //小时
"m+": date.getMinutes(), //分
"s+": date.getSeconds(), //秒
"q+": Math.floor((date.getMonth() + 3) / 3), //季度
"S": date.getMilliseconds() //毫秒
};
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (const k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
}
return format;
}
};
```
该工具类提供了一个 formatDate 方法,可以将 Date 对象格式化为指定格式的字符串。使用方法如下:
```javascript
const date = new Date();
const formatStr = "yyyy-MM-dd hh:mm:ss";
const formattedDate = DateFormatUtil.formatDate(date, formatStr);
console.log(formattedDate); // 输出:2022-01-01 13:30:00
```
在上面的代码中,我们首先创建了一个 Date 对象,然后定义了一个格式化字符串 formatStr,最后调用了 DateFormatUtil.formatDate 方法将 Date 对象格式化为指定格式的字符串。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)