The difference between uniapp (js) processing the past time and the current time is like a few minutes ago, a few hours ago, and a few months ago (modeled on the cnode community)

Look at the code first and copy and use it. However, it is recommended that you read it and organize your thoughts. In general, the thoughts are very important, followed by the code.

You will see the following effect

Time comparison

<template>
	<view>
		发表时间 <span style="color:red">{
    
    {
    
    outTime}}</span> 是现在的 <span style="color:red">{
    
    {
    
    nowTimer | formatDate}}</span>
	</view>
</template>
<script>
	export default {
    
    
		data() {
    
    
			return {
    
    
				//一个过去时间
				outTime: '2020/09/17 10:44:10',
				nowTimer: 0
			}
		},
		created() {
    
    
			this.nowTimer = new Date(this.outTime).getTime()
		},
		filters: {
    
    

			formatDate: (nowTimer) => {
    
    
				let formats = {
    
    
					'year': '几 年前',
					'month': '几 月前',
					'day': '几 天前',
					'hour': '几 小时前',
					'minute': '几 分钟前',
					'second': '几 秒前',
				};
				//获取当前时间戳
				let now = Date.now();
				let seconds = Math.floor((now - parseInt(nowTimer)) / 1000);
				let minutes = Math.floor(seconds / 60);
				let hours = Math.floor(minutes / 60);
				let days = Math.floor(hours / 24);
				let months = Math.floor(days / 30);
				let years = Math.floor(months / 12);
				let oldType = '';
				let oldValue = 0;
				if (years > 0) {
    
    
					//几年前
					oldType = 'year';
					oldValue = years;
				} else {
    
    
					if (months > 0) {
    
    
						//几个月前
						oldType = 'month';
						oldValue = months;
					} else {
    
    
						if (days > 0) {
    
    
							//几天前
							oldType = 'day';
							oldValue = days;
						} else {
    
    
							if (hours > 0) {
    
    
								//几小时前
								oldType = 'hour';
								oldValue = hours;
							} else {
    
    
								//这里  您可以处理一个  刚刚  比如时间小于30分钟
								if (minutes > 0) {
    
    
									//几分钟前   
									oldType = 'minute';
									oldValue = minutes;
								} else {
    
    
									//几秒前 
									oldType = 'second';
									oldValue = seconds === 0 ? (seconds = 1) : seconds;
								}
							}
						}
					}
				}
				return formats[oldType].replace('几', oldValue);
			}

		}
	}
</script>

Additional and useful information that may appear has been commented.
Other questions about uniapp or areas that you do not understand this method can leave a message, I will reply and help you solve it as soon as possible.

Guess you like

Origin blog.csdn.net/weixin_47821281/article/details/108638666
Recommended