文章目录
- 1. 返回的报文
- 2. 时间格式化方法
- 3. 使用
1. 返回的报文
格式化时间:createTime
[{"id": "62c11d3435b7c4007a8e650e","fromUserId": "21100598TZ9XG6RP","fromNickname": "小美女","fromFace": "http://gblfy.cn:9000/imooc/xh.jpg","toUserId": "220620BZ2DH0KP94","msgType": 1,"msgContent": {"isFriend": true},"createTime": "2022-07-03 12:38:11"
}
...其他的数据省略
]
2. 时间格式化方法
App.vue定义全局方法,便于调用,单独抽取出来放到工具类中也可以
methods: {// 时间格式化时间为:刚刚、多少分钟前、多少天前// stringTime 2020-09-10 20:20:20getDateBeforeNow(stringTime) {console.log("传参未格式化", stringTime);stringTime = new Date(stringTime.replace(/-/g, '/'))// 统一单位换算var minute = 1000 * 60;var hour = minute * 60;var day = hour * 24;var week = day * 7;var month = day * 30;var year = month * 12;var time1 = new Date().getTime(); //当前的时间戳console.log("当前时间", time1);// 对时间进行毫秒单位转换var time2 = new Date(stringTime).getTime(); //指定时间的时间戳console.log("传过来的时间", time2);var time = time1 - time2;console.log("计算后的时间", time);var result = null;if (time < 0) {// alert("设置的时间不能早于当前时间!");result = stringTime;} else if (time / year >= 1) {result = parseInt(time / year) + "年前";} else if (time / month >= 1) {result = parseInt(time / month) + "月前";} else if (time / week >= 1) {result = parseInt(time / week) + "周前";} else if (time / day >= 1) {result = parseInt(time / day) + "天前";} else if (time / hour >= 1) {result = parseInt(time / hour) + "小时前";} else if (time / minute >= 1) {result = parseInt(time / minute) + "分钟前";} else {result = "刚刚";}console.log("格式化后的时间", result);return result;},
}
3. 使用
页面
<template><view class="msg-item-middle"><text class="user-nickname">{{msg.fromNickname}}</text><text class="msg-content">关注了你 {{getGraceDateBeforeNow(msg.createTime)}}</text></view>
</template>
方法区
<script>var app = getApp();
export default {methods: {// 时间显示优化 刚刚、几分钟前,几小时前,几个月前getGraceDateBeforeNow(dateTimeStr) {return getApp().getDateBeforeNow(dateTimeStr);},}
}
</script>