例1:js将时间转换为几分钟前,几小时前,几天前的方法
function timeFormat(time) {
var nowTime = new Date();
var day = nowTime.getDate();
var hours = parseInt(nowTime.getHours());
var minutes = nowTime.getMinutes();
// 开始分解付入的时间
var timeday = time.substring(8, 10);
var timehours = parseInt(time.substring(11, 13));
var timeminutes = time.substring(14, 16);
var d_day = Math.abs(day - timeday);
var d_hours = hours - timehours;
var d_minutes = Math.abs(minutes - timeminutes);
if (d_day <= 1) {
switch (d_day) {
case 0:
if (d_hours == 0 && d_minutes > 0) {
return d_minutes + '分钟前';
} else if (d_hours == 0 && d_minutes == 0) {
return '1分钟前';
} else {
return d_hours + '小时前';
}
break;
case 1:
if (d_hours < 0) {
return (24 + d_hours) + '小时前';
} else {
return d_day + '天前';
}
break;
}
} else if (d_day > 1 && d_day < 10) {
return d_day + '天前';
} else {
return time;
}
}
console.log(timeFormat("2020-06-23 23:10:02")); //37分钟前
console.log(timeFormat("2020-06-23 22:10:02")); //1小时前
console.log(timeFormat("2020-06-22 22:10:02")); //1天前
console.log(timeFormat("2020-06-21 22:10:02")); //2天前
例2:js将时间转换为几分钟前,几小时前,几天前的方法
- 例1的 js 演示函数,可以输入日期格式的时间日期,其方法比较复杂一些,那么接下来就来一个简单点的,直接输入时间戳!
//这里输入的时间戳
function timeFormat(timestamp) {
var mistiming = Math.round((Date.now() - timestamp) / 1000);
var arrr = ['年', '个月', '周', '天', '小时', '分钟', '秒'];
var arrn = [31536000, 2592000, 604800, 86400, 3600, 60, 1];
for (var i = 0; i < arrn.length; i++) {
var inm = Math.floor(mistiming / arrn[i]);
if (inm != 0) {
return inm + arrr[i] + '前';
}
}
}
console.log(timeFormat(1592928599000)); //10秒前
console.log(timeFormat(1592928469000)); //2分钟前
console.log(timeFormat(1592844949000)); //23小时前
console.log(timeFormat(1592064469000)); //1周前
console.log(timeFormat(1581844949000)); //4个月前
console.log(timeFormat(1522444949000)); //2年前
评论 (0)