// 日期格式化
export function parseTime(time, pattern) {
if (arguments.length === 0 || !time) {
return null
}
const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
time = parseInt(time)
} else if (typeof time === 'string') {
time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
}
if ((typeof time === 'number') && (time.toString().length === 10)) {
time = time * 1000
}
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
let value = formatObj[key]
// Note: getDay() returns 0 on Sunday
if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
return time_str
}
使用说明
定义好函数后传两个参数,第一个是 时间戳 或 new Date(),第二个是要转换的格式,非必传。
如 console.log(parseTime(new Date(), '{y}年{m}月{d}日 周{a} 时间{h}:{i}:{s}'))
花括号中会正则,对应年月日,周,时分秒,花括号外的作为自定义字符原样返回
补充
endOfStartTime: (startTime, endTime) => {
let result = {
day: '00',
hou: '00',
min: '00',
sec: '00',
signs: 0
}
if (endTime - startTime > 0) {
const time = (endTime - startTime) / 1000 // 获取天、时、分、秒
const day = parseInt(time / (60 * 60 * 24))
const hou = parseInt(time % (60 * 60 * 24) / 3600)
const min = parseInt(time % (60 * 60 * 24) % 3600 / 60)
const sec = parseInt(time % (60 * 60 * 24) % 3600 % 60)
result = {
day: `${util.timeFormat(day)}`,
hou: `${util.timeFormat(hou)}`,
min: `${util.timeFormat(min)}`,
sec: `${util.timeFormat(sec)}`,
signs: 1
}
}
return result
},
传入开始时间戳和结束时间戳返回间隔时间