一个自定义返回格式的时间戳解析函数
y 年 M 月 d 天 h 小时 m 分钟 s秒
// 三个参数 时间戳 自定义拼接格式 是否补0
console.log(timeProcessor(1664178400000, 'y-M月-d h时m:s',true)); //2022-9月-26 15时46:40
console.log(timeProcessor(1664178400000, 'M-d')); //09-26
console.log(timeProcessor(1664178400000)); //2022-09-26 15:46:40
函数如下
const timeProcessor = (time: number | null, type?:string,dontFill?:boolean):string =>{
if(!time) return '-';
if(String(time).length < 13) {
time *= 1000;
}
const date = new Date(time);
const year = date.getFullYear();
let month = (date.getMonth() + 1).toString().padStart(2, '0');
let day = date.getDate().toString().padStart(2, '0');
let hour = date.getHours().toString().padStart(2, '0');
let min = date.getMinutes().toString().padStart(2, '0');
let sec = date.getSeconds().toString().padStart(2, '0');
if(dontFill){
month = Number(month) + '';
day = Number(day) + '';
hour = Number(hour) + '';
min = Number(min) + '';
sec = Number(sec) + '';
}
if(!type) return `${year}-${month}-${day} ${hour}:${min}:${sec}`;
try {
return Array.from(type).map(i=>{
switch (i){
case 'y': return year;
case 'M': return month;
case 'd': return day;
case 'h': return hour;
case 'm': return min;
case 's': return sec;
default:return i;
}
}).join('');
}catch (err){
return `${year}:${month}:${day} ${hour}:${min}:${sec}`
}
};