时间戳转换时间
在微博,每条微博的发表时间并不是标准的yy-dd-hh这种格式,而是如:“几分钟前”、“几小时前”这样的,比起标准的时间显示格式,貌似更加直观和人性化。本文就是实现这种将时间戳转换为展示的时间
code
class TimeChange{
constructor(time){
this.minutes = 1000 * 60;
this.hour = this.minutes * 60;
this.day = this.hour * 24;
this.month = this.day * 30;
this.timeStampS = time;
}
getDiffTime(){
let diffValue = Date.parse(new Date()) - this.timeStampS;
return diffValue;
}
getTime(){
let diffTime = this.getDiffTime();
if(diffTime < 0){
alert('日期不对!');
return;
}
let monthC = Math.floor(diffTime / this.month);
let diffDays = diffTime - monthC * this.month;
let dayC = Math.floor(diffDays / this.day);
let diffHours = diffDays - dayC * this.day;
let hourC = Math.floor(diffHours / this.hour);
let diffMinutes = diffHours - hourC * this.hour;
let minC = Math.floor(diffMinutes / this.minutes);
let timeStr = (monthC >= 1 ? monthC : 0) + '个月,' + (dayC >= 1 ? dayC : 0) + '天,' + (hourC >=1 ? hourC : 0) + '个小时,' + (minC >=1 ? minC : 0) + '分钟前';
console.log(timeStr);
return timeStr;
}
}
该方法是将后台获取的时间戳与当前时间进行比对进而得出时间差,然后将这个时间差转换成月、日、小时这种的格式,调用方法为
const time = new TimeChange('1503108271000'); // 这里是后台获取的时间戳
time.getTime();
本文纯手打,有不当之处请留言,会尽快处理!谢谢