//date可以是时间戳,也可以是2020/10/10类似这种形式的时间字符串
formatDate(date, fmt) {
if (!date) {
return '';
}
date = new Date(date);
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
let o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
}
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + ''
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length))
}
}
return fmt
}
//示例:formatDate(new Date(), 'yyyy年MM月dd日')
//formatDate(new Date(), 'yyyy-MM-dd')
时间戳转换各种形式的日期格式
最新推荐文章于 2022-10-11 23:06:59 发布
本文介绍了一种使用JavaScript实现的日期格式化方法,该方法能够将时间戳或特定格式的日期字符串转换为用户自定义格式的日期字符串。示例中提供了如何使用此方法的具体代码。
2337

被折叠的 条评论
为什么被折叠?



