跳到主要内容

js时间几天前,几小时前,几分钟前

· 阅读需 3 分钟
lzw.

简单写法

function FormatTime(timestamp) {
var mistiming = Math.round(new Date() / 1000) - timestamp;
var postfix = mistiming > 0 ? '前' : '后'
mistiming = Math.abs(mistiming)
var arrr = ['年', '个月', '星期', '天', '小时', '分钟', '秒'];
var arrn = [31536000, 2592000, 604800, 86400, 3600, 60, 1];
for (var i = 0; i < 7; i++) {
var inm = Math.floor(mistiming / arrn[i])
if (inm != 0) {
return inm + arrr[i] + postfix
}
}
}

更想详细写法

var Time = {
// 获取当前时间戳
getUnix: function () {
var date = new Date();
return date.getTime();
},
// 获取今天0点0分0秒的时间戳
getTodayUnix: function () {
var date = new Date();
date.setHours(0); //设置指定时间的小时字段
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date.getTime();
},
// 获取今年1月1日0点0分0秒的时间戳
getYearUnix: function () {
var date = new Date();
date.setMonth(0)
date.setDate(1);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date.getTime();
},
// 获取标准年月日
getLastDate: function (time) {
var date = new Date(time);
var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
return date.getFullYear() + '-' + month + '-' + day
},
// 转换时间
getFormatTime: function (timestamp) {
var now = this.getUnix(); //当前时间戳
var today = this.getTodayUnix(); //今天0点时间戳
var year = this.getYearUnix(); //今年0点时间戳
var timer = (now - timestamp) / 1000; //转化为秒级时间戳
var tip = '';
// 1分钟以前,显示“刚刚”。
// 1分钟~1小时之间,显示“xx分钟前”。
// 1小时~1天之间,显示“xx小时前”。
// 1天~1个月(31天)之间,显示“xx天前”。
// 大于1个月,显示“xx年xx月xx日”。
if (timer <= 0) {
tip = '刚刚';
} else if (Math.floor(timer / 60) <= 0) {
tip = '刚刚'
} else if (timer < 3600) {
tip = Math.floor(timer / 60) + '分钟前';
} else if (timer >= 3600 && (timestamp - today >= 0)) {
tip = Math.floor(timer / 3600) + '小时前'
} else if (timer / 86400 <= 31) {
tip = Math.ceil(timer / 86400) + '天前'
} else {
tip = this.getLastDate(timestamp);
}
return tip;
}
}