版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32768743/article/details/83896170
不记得从哪里抄过来的,用了几次,还挺好用的,留在这里做个记录。
百度一下,上Google应该很快能搜到相关的代码。
话说js不直接提供格式化的方法吗?还是我不知道呢?
export const dateTime = {
/**
* 根据标准时间格式(yyyy-MM-dd HH:mm:ss)获得时间
*/
getDateByFormat (dateStr) {
dateStr = dateStr.replace('-', '/')
return new Date(Date.parse(dateStr))
},
/**
* 根据模板获得时间的格式化
*/
dateFormat (date, formatStr = 'yyyy-MM-dd HH:mm:ss') {
// 转换成Date类型
date = new Date(date)
const opt = {
'yyyy': date.getFullYear(),
'MM': addZero(date.getMonth() + 1),
'M': date.getMonth() + 1,
'dd': addZero(date.getDate()),
'd': date.getDate(),
'HH': addZero(date.getHours()),
'H': date.getHours(),
'mm': addZero(date.getMinutes()),
'm': date.getMinutes(),
'ss': addZero(date.getSeconds()),
's': date.getSeconds()
}
// 如果是个位数则前面添加0
function addZero (value) {
return value < 10 ? '0' + value : value
}
// 遍历替换
for (const k in opt) {
formatStr = formatStr.replace(k, opt[k])
}
return formatStr
},
/**
* 标准时间格式
*/
formatPattern: 'yyyy-MM-dd HH:mm:ss'
}