新建一个formatDate.js文件,如下:
function padLeftZero(str) {
return ('00' + str).substr(str.length)
}
export function formatDate(date, fmt) {
if (!date) {
return ''
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
(date.getFullYear() + '').substr(4 - RegExp.$1.length)
)
}
const o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
}
for (const k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
const str = o[k] + ''
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length === 1 ? str : padLeftZero(str)
)
}
}
return fmt
}
export default formatDate
如果是在vue项目中运用,在main.js中全局引用
import formatDate from '@/utils/formatDate.js'
Vue.prototype.$formatDate = formatDate
再到页面上直接调用$formatDate方法
// 获取当前时间年月日时分秒,即 2022-10-14 16:11:58
this.$formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
// 如果时分秒不需要精确到,即 2022-10-14 00:00:00
this.$formatDate(new Date(), 'yyyy-MM-dd 00:00:00')
// 意思就是说时分秒你需要什么时间就写什么时间;需要是下午4点11分58秒,即 2022-10-14 16:11:58
this.$formatDate(new Date(), 'yyyy-MM-dd 16:11:58')