JS(JavaScript)格式化时间显示
- JavaScript
- 2024-07-21
- 204热度
- 0评论
做时间渲染的时候,经常会遇到需要将时间转为特定的显示方式,以下是常见的时间显示格式化方法:
export function formateTime(timeStamp){
timeStamp = timeStamp * 1000;
let date = new Date(timeStamp);
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
let hour = date.getHours();
let minute = date.getMinutes();
let nowTime = new Date().getTime();
let diff = nowTime - timeStamp;
diff = parseInt(diff / 1000);
if(diff < 60){ return '刚刚'; }
if(diff < 3600){ return Math.ceil(diff / 60) + '分钟前'; }
if(diff < 86400){ return (hour < 10 ? '0' + hour : hour) + ':' + (minute < 10 ? '0' + minute : minute);}
return year + '-' + month + '-' + day + ' ' + (hour < 10 ? '0' + hour : hour) + ':' + (minute < 10 ? '0' + minute : minute);
}