经常看到一些时间提示是
1小时前
,2分钟前
,3天前
等等的差距时间,这些是怎么实现的呢?看下面的方法!
代码实现
function timeDifference(tmpTime) {
var mm = 1000;
var minute = mm * 60;
var hour = minute * 60;
var day = hour * 24;
var month = day * 30;
var ansTimeDifference = 0;
var tmpTimeStamp = tmpTime ? Date.parse(tmpTime.replace(/-/gi, "/")) : new Date().getTime();
var nowTime = new Date().getTime();
var tmpTimeDifference = nowTime - tmpTimeStamp;
if (tmpTimeDifference < 0) {
console.warn("开始日期大于结束日期,计算失败!");
return 0;
}
var DifferebceMonth = tmpTimeDifference / month;
var DifferebceWeek = tmpTimeDifference / (7 * day);
var DifferebceDay = tmpTimeDifference / day;
var DifferebceHour = tmpTimeDifference / hour;
var DifferebceMinute = tmpTimeDifference / minute;
if (DifferebceMonth >= 1) {
return tmpTime;
} else if (DifferebceWeek >= 1) {
ansTimeDifference = parseInt(DifferebceWeek) + "个星期前";
} else if (DifferebceDay >= 1) {
ansTimeDifference = parseInt(DifferebceDay) + "天前";
} else if (DifferebceHour >= 1) {
ansTimeDifference = parseInt(DifferebceHour) + "个小时前";
} else if (DifferebceMinute >= 1) {
ansTimeDifference = parseInt(DifferebceMinute) + "分钟前";
} else {
ansTimeDifference = "刚刚";
}
return ansTimeDifference;
};
评论 (0)