方法一:
1、字符串时间转换为时间戳
// 字符串时间转换为时间戳
getDateTimeStamp (dateStr) {
return Date.parse(dateStr.replace(/-/gi,"/"));
}
2、时间戳格式化成 ==几小时前
==
// 时间格式化函数
timeTampFormat(timestamp){
var mistiming=Math.round(new Date() / 1000)- Math.round( getDateTimeStamp(timestamp)/1000);
var arrr = ['年','个月','星期','天','小时','分钟','秒'];
var arrn = [31536000,2592000,604800,86400,3600,60,1];
for(var i=0;i<=6;i++){
var inm = Math.floor(mistiming/arrn[i]);
if(inm!=0){
return inm+arrr[i]+'前';
}
}
},
方法二:
getDateDiff (dateStr) {
// 获取指定时间的时间戳
var publishTime = getDateTimeStamp(dateStr)/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){
return d_days + '天前';
}else if(d_days <= 0 && d_hours > 0){
return d_hours + '小时前';
}else if(d_hours <= 0 && d_minutes > 0){
return d_minutes + '分钟前';
}else if (d_seconds < 60) {
if (d_seconds <= 0) {
return '刚刚';
}else {
return d_seconds + '秒前';
}
}else if (d_days >= 3 && d_days < 30){
return M + '-' + D + ' ' + H + ':' + m;
}else if (d_days >= 30) {
return Y + '-' + M + '-' + D + ' ' + H + ':' + m;
}
}
网友评论