获取类似朋友圈的时间显示算法
function getDateDiff(date) {
var publishTime = date / 1000,
d_seconds,
d_minutes,
d_hours,
d_days,
timeNow = parseInt(new Date().getTime() / 1000),
d,
date = new Date(publishTime * 1000),
Y = date.getFullYear(), //获取当前年份
M = date.getMonth() + 1, //获取当前月份
D = date.getDate(), //获取当前天数
H = date.getHours(), //获取当前小时
m = date.getMinutes(), //获取当前分钟
s = date.getSeconds(); //获取当前秒
//小于10的在前面补0
if (M < 10) {
M = '0' + M;
}
if (D < 10) {
D = '0' + D;
}
if (H < 10) {
H = '0' + H;
}
if (m < 10) {
m = '0' + m;
}
if (s < 10) {
s = '0' + s;
}
d = timeNow - publishTime; //计算时间差
d_days = parseInt(d / 86400); //计算差几天
d_hours = parseInt(d / 3600); //计算差几个小时
d_minutes = parseInt(d / 60); //计算差多少分钟
d_seconds = parseInt(d); //计算差多少秒
if (d_days > 0 && d_days < 3) { //3天之内
return d_days + '天前';
} else if (d_days <= 0 && d_hours > 0) { //1天之内显示小时
return d_hours + '小时前';
} else if (d_hours <= 0 && d_minutes > 0) { //1小时之内显示分钟
return d_minutes + '分钟前';
} else if (d_seconds < 60) { //1分钟内 显示秒
if (d_seconds <= 0) {
return '刚刚';
} else {
return d_seconds + '秒前';
}
} else if (d_days >= 3 && d_days < 30) { //30天之内不显示年份
return M + '-' + D + ' ' + H + ':' + m;
} else if (d_days >= 30) { //大于30天显示年份
return Y + '-' + M + '-' + D + ' ' + H + ':' + m;
}
}
使用时只需要将记录的时间传进去就ok
console.log(getDateDiff(new Date().getTime()-1000));
==>刚刚
console.log(getDateDiff(new Date().getTime()-10000));
==>9秒前
console.log(getDateDiff(new Date().getTime()-100000));
==>1分钟前
console.log(getDateDiff(new Date().getTime()-10000000));
==>2小时前
console.log(getDateDiff(new Date().getTime()-100000000));
==>1天前
console.log(getDateDiff(new Date().getTime()-1000000000));
==>05-16 03:22
console.log(getDateDiff(new Date().getTime()-10000000000));
==>2019-01-31 23:22
网友评论