在methods中创建方法showtime,传入要跟当前时间要对比的时间 showtime(time) { let date = typeof time === "number" new Date(time) : new Date((time || "").replace(/-/g, "/")); let diff = (new Date().getTime() - date.getTime(
在methods中创建方法showtime,传入要跟当前时间要对比的时间
showtime(time) { let date = typeof time === "number" ? new Date(time) : new Date((time || "").replace(/-/g, "/")); let diff = (new Date().getTime() - date.getTime()) / 1000; let dayDiff = Math.floor(diff / 86400); let isValidDate = Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date.getTime()); if (!isValidDate) { window.console.error("不是有效日期格式"); } const formatDate = function(date) { let today = new Date(date); let year = today.getFullYear(); let month = ("0" + (today.getMonth() + 1)).slice(-2); let day = ("0" + today.getDate()).slice(-2); let hour = today.getHours(); let minute = today.getMinutes(); let second = today.getSeconds(); return `${year}-${month}-${day} ${hour}:${minute}:${second}`; }; if (isNaN(dayDiff) || dayDiff < 0 || dayDiff >= 31) { return formatDate(date); } return ( (dayDiff === 0 && ((diff < 60 && "刚刚") || (diff < 120 && "1分钟前") || (diff < 3600 && Math.floor(diff / 60) + "分钟前") || (diff < 7200 && "1小时前") || (diff < 86400 && Math.floor(diff / 3600) + "小时前"))) || (dayDiff === 1 && "昨天") || (dayDiff < 7 && dayDiff + "天前") || (dayDiff < 31 && Math.ceil(dayDiff / 7) + "周前") ); },
补充知识:Vue中根据时间戳计算时间间隔-年龄
实现目标
由于数据库没有直接存储用户的年龄,只有以时间戳为格式的出生日期,所以不得不在前端做一下计算处理。下面就和大家一起来看一下前端JS的实现方法。
功能代码
由于时间戳是包含了具体时间的,所以在转日期后截取年月日部分即可。
再获取当前的时期计算间隔得出用户的年龄。
// 获取用户年龄 this.userAge = this.toAge(timeStamp); console.log(this.userAge); // 根据返回的日期计算间隔 toAge(timeStamp) { let birthDate = this.toDate(timeStamp).substr(0, 4); let newDate = new Date().getFullYear(); return (newDate - parseInt(birthDate)); } // 时间戳转日期 toDate(number) { let n = number; let date = new Date(n); let Y = date.getFullYear() + '/'; let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/'; let D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(); return (Y + M + D) }
内容小结
又是一个小功能的实现,一边记录下自己的代码,一边和大家分享平时代码的点滴,希望能给大家一个参考,也希望大家多多支持易盾网络。