js 日期昨天 前天 今天函数

		// 格式化时间
		formatTime(time){
			// "2019-08-07 10:53:00"
			_time = time.replace(/-/g,"/")
			let publishTime = new Date(_time).getTime()
			let nowTime = new Date().getTime()
			
			// 不同时间的时间戳
			const twentyFourHours = 24 * 60 * 60 * 1000;
			const oneMin = 60 * 1000;
			const fiveteenMin = 15 * 60 * 1000;
			const thirtyMin = 30 * 60 * 1000;
			const oneHour = 60 * 60 * 1000;

			const date = new Date();
			const year = date.getFullYear();
			const month = date.getMonth() + 1;
			const day = date.getDate();
			const today = `${year}/${month}/${day}`;
			const todayTime = new Date(today).getTime();

			const yesterdayTime = new Date(todayTime - twentyFourHours).getTime();
			const lastYesterdayTime = new Date(todayTime - twentyFourHours*2).getTime();
			const lastThreeDays = new Date(todayTime - twentyFourHours*3).getTime();
			const lastFourDays = new Date(todayTime - twentyFourHours*4).getTime();
			const lastFiveDays = new Date(todayTime - twentyFourHours*5).getTime();
			const lastSixDays = new Date(todayTime - twentyFourHours*6).getTime();
			const lastSevenDays = new Date(todayTime - twentyFourHours*7).getTime();

			if (publishTime >= todayTime) {
				if (nowTime - publishTime < thirtyMin) {
					return Math.floor(new Date(nowTime - publishTime) / (60 * 1000)) + "分钟前"
				} else if (thirtyMin <= nowTime - publishTime && nowTime - publishTime < oneHour) {
					return "半小时前"
				} else {
					return Math.floor(new Date(nowTime - publishTime) / (60 * 60 * 1000)) + "小时前"
				}
			}
			else if (yesterdayTime <= publishTime && publishTime < todayTime) {
				return '昨天 ' + _time.split(' ')[1];
			}
			else if (lastYesterdayTime <= publishTime && publishTime < yesterdayTime) {
				return '前天 ' + _time.split(' ')[1];
			}
			else if (lastThreeDays <= publishTime && publishTime < lastYesterdayTime) {
				return '3天前';
			}
			else if (lastFourDays <= publishTime && publishTime < lastThreeDays) {
				return '4天前';
			}
			else if (lastFiveDays <= publishTime && publishTime < lastFourDays) {
				return '5天前';
			}
			else if (lastSixDays <= publishTime && publishTime < lastFiveDays) {
				return '6天前';
			}
			else if (lastSevenDays <= publishTime && publishTime < lastSixDays) {
				return '7天前';
			}
			else {
				return time.split(' ')[0];
			}
		}
formatTime(2019-08-07 10:53:00)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值