毫秒转成刚刚/几分钟前/几小时前几天前/几周前/几个月前

学习别人的,哪个地址我给忘了,这是后来才写的博文
简单说就是获取到当前时间的值然后比对

timeago = (datetime) => { //dateTimeStamp是一个时间毫秒,注意时间戳是秒的形式,在这个毫秒的基础上除以1000,就是十位数的时间戳。13位数的都是时间毫秒。
	console.log(datetime,typeof datetime)
	
	var dateTimeStamp = new Date(datetime).getTime()-8 * 60 * 60 * 1000;//这里要减去中国的时区8小时
	console.log(dateTimeStamp)
	var minute = 1000 * 60; //把分,时,天,周,半个月,一个月用毫秒表示
	var hour = minute * 60; 
	var day = hour * 24;
	var week = day * 7;
	var halfamonth = day * 15;
	var month = day * 30;
	var now = new Date().getTime(); //获取当前时间毫秒
	var diffValue = now - dateTimeStamp; //时间差
	
	if (diffValue < 0) {
		console.log("diffValue<0",datetime,dateTimeStamp,now,diffValue);
		return '刚刚';
	}
	var minC = diffValue / minute; //计算时间差的分,时,天,周,月
	var hourC = diffValue / hour;
	var dayC = diffValue / day;
	var weekC = diffValue / week;
	var monthC = diffValue / month;
	var result = "2";
	if (monthC >= 1 && monthC <= 3) {
		result = " " + parseInt(monthC) + "月前"
	} else if (weekC >= 1 && weekC <= 3) {
		result = " " + parseInt(weekC) + "周前"
	} else if (dayC >= 1 && dayC <= 6) {
		result = " " + parseInt(dayC) + "天前"
	} else if (hourC >= 1 && hourC <= 23) {
		result = " " + parseInt(hourC) + "小时前"
	} else if (minC >= 1 && minC <= 59) {
		result = " " + parseInt(minC) + "分钟前"
	} else if (diffValue >= 0 && diffValue <= minute) {
		result = "刚刚"
	} else {
		var datetime = new Date();
		datetime.setTime(dateTimeStamp);
		console.log(datetime);
		var Nyear = datetime.getFullYear(); {}
		var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
		var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
		var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
		var Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
		var Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
		console.log(Nyear,Nmonth,Ndate,Nhour,Nminute,Nsecond	)
		result = Nyear + "-" + Nmonth + "-" + Ndate
	}
	console.log(result);
	return result;
}
timeago(1592452611000);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值