时间戳转换为刚刚、几分钟前 ...

JavaScript 将时间戳转换为刚刚、几分钟前、几小时前、几天前 ... 代码分享 :

相关函数

fromTime

将时间戳转换为刚刚、几分钟前、几小时前、几天前

toDate

将时间戳转换为日期时间

完整代码

<template>
	<view>
		{{fromTime(1643170590)}}
	</view>
</template>
<script>
export default {
	methods:{
		// 将时间戳转换为刚刚、几分钟前、几小时前、几天前
		fromTime : function(time){
		    if(time < 90000000000 ){time *= 1000;}
		    var timer = new Date().getTime() - time;
		    timer = parseInt(timer / 1000);
		    if(timer < 180){
		        return '刚刚';
		    }else if(timer >= 180 && timer < 3600){
		        return parseInt(timer / 60) + '分钟前';
		    }else if(timer >= 3600 && timer < 86400){
		        return parseInt(timer / 3600) + '小时前';
		    }else if(timer >= 86400 && timer < 2592000){
		        return parseInt(timer / 86400) + '天前';
		    }else{
		        return this.toDate(time, 'str');
		    }
		},
		// 时间戳转换为日期时间
		toDate : function(timeStamp, returnType){
		    timeStamp = parseInt(timeStamp);
		    var date = new Date();
		    if(timeStamp < 90000000000 ){
		        date.setTime(timeStamp * 1000);
		    }else{
		        date.setTime(timeStamp );
		    }
		    var y = date.getFullYear();
		    var m = date.getMonth() + 1;
		    m = m < 10 ? ('0' + m) : m;
		    var d = date.getDate();
		    d = d < 10 ? ('0' + d) : d;
		    var h = date.getHours();
		    h = h < 10 ? ('0' + h) : h;
		    var minute = date.getMinutes();
		    var second = date.getSeconds();
		    minute = minute < 10 ? ('0' + minute) : minute;
		    second = second < 10 ? ('0' + second) : second;
		    if(returnType == 'str'){return y + '-' + m + '-' + d + ' '+ h +':' + minute + ':' + second;}
		    return [y, m, d, h, minute, second];
		}
	}
}
</script>
<style>
</style>