1.秒 转 天、时、分、秒
//将秒转化为天时分秒
export function formateSeconds(s){
var day = Math.floor( s/ (24*3600) ); // Math.floor()向下取整
var hour = Math.floor( (s - day*24*3600) / 3600);
var minute = Math.floor( (s - day*24*3600 - hour*3600) /60 );
var second = s - day*24*3600 - hour*3600 - minute*60;
return day + "天" + hour + "时" + minute + "分" + second + "秒";
}
如果不足天 return => 0天0时5分15秒
export function getDuration(second) {
var duration
var days = Math.floor(second / 86400);
var hours = Math.floor((second % 86400) / 3600);
var minutes = Math.floor(((second % 86400) % 3600) / 60);
var seconds = Math.floor(((second % 86400) % 3600) % 60);
if(days>0) duration = days + "天" + hours + "小时" + minutes + "分" + seconds + "秒";
else if(hours>0) duration = hours + "小时" + minutes + "分" + seconds + "秒";
else if(minutes>0) duration = minutes + "分" + seconds + "秒";
else if(seconds>0) duration = seconds + "秒";
return duration;
}
如果不足天 return => 5分15秒
2.秒 转 几分钟前,刚刚
export function formatTime(time) {
if (('' + time).length === 10) {
time = parseInt(time) * 1000
} else {
time = +time
}
const d = new Date(time)
const now = Date.now()
const diff = (now - d) / 1000
if (diff < 30) {
return '刚刚'
} else if (diff < 3600) {
// less 1 hour
return Math.ceil(diff / 60) + '分钟前'
} else if (diff < 3600 * 24) {
return Math.ceil(diff / 3600) + '小时前'
} else if (diff < 3600 * 24 * 2) {
return '1天前'
}
}
直接放util里,使用的时候引用即可