2021-05-15(修改时间)
转换时间格式
月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q)
年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
fmt 时间格式
const DateFormatG = function (fmt) {
let date = new Date();
let tempVal = fmt;
let 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(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (let k in o) {
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
return tempVal == fmt ? console.warn(`请输入正确时间转换格式,当前格式${tempVal}`) : fmt;
}通过时间戳转换格式
可以自定义日期显示格式Y/y(年),M/m(月),D/d(日),H/h(时),I/i(分),S/s(秒) (字母大写补0,小写不补0) 如 H:03 h:3
time 时间戳
fmt 自定义时间格式,可以为空
const DateFormatNumG = function (time, fmt) {
const t = new Date(time)
// 日期格式
fmt = fmt || 'Y-M-D H:I:S'
const hash = {
'y': t.getFullYear(),
'm': t.getMonth() + 1,
'd': t.getDate(),
'h': t.getHours(),
'i': t.getMinutes(),
's': t.getSeconds()
}
// 是否补 0
const isAddZero = (o) => {
return /M|D|H|I|S/.test(o)
}
return fmt.replace(/\w/g, o => {
let rt = hash[o.toLocaleLowerCase()]
return rt >= 10 || !isAddZero(o) ? rt : `0${rt}`
})
}