|
1 | 1 | import CryptoJS from 'crypto-js' |
2 | 2 | import sysConfig from '@/config' |
3 | 3 |
|
| 4 | +import dayjs from 'dayjs' |
| 5 | +import relativeTime from 'dayjs/plugin/relativeTime' |
| 6 | + |
| 7 | +// 扩展插件和语言设置 |
| 8 | +dayjs.extend(relativeTime) |
| 9 | + |
4 | 10 | const tool = {} |
5 | 11 |
|
6 | 12 | tool.time = { |
@@ -38,27 +44,35 @@ tool.time = { |
38 | 44 | }, |
39 | 45 | //转换时间 |
40 | 46 | getFormatTime: function (_this, timestamp) { |
41 | | - timestamp = new Date(timestamp) |
42 | | - const now = this.getUnix() |
43 | | - const today = this.getTodayUnix() |
44 | | - //var year = this.getYearUnix(); |
45 | | - const timer = (now - timestamp) / 1000 |
46 | | - let tip |
| 47 | + if (!timestamp) return '--' |
| 48 | + |
| 49 | + const now = dayjs() |
| 50 | + const target = dayjs(timestamp) |
| 51 | + const diffSeconds = now.diff(target, 'second', true) |
| 52 | + const isFuture = diffSeconds < 0 // 是否未来时间 |
| 53 | + const absDiff = Math.abs(diffSeconds) // 时间差绝对值 |
| 54 | + |
| 55 | + // 超过10天(10 * 24 * 60 * 60 秒)显示具体日期 |
| 56 | + if (absDiff > 10 * 86400) { |
| 57 | + return target.format('YYYY-MM-DD') |
| 58 | + } |
47 | 59 |
|
48 | | - if (timer <= 0) { |
49 | | - tip = _this.$t('刚刚') |
50 | | - } else if (Math.floor(timer / 60) <= 0) { |
51 | | - tip = _this.$t('刚刚') |
52 | | - } else if (timer < 3600) { |
53 | | - tip = _this.$t('{n} 分钟前', { n: Math.floor(timer / 60) }) |
54 | | - } else if (timer >= 3600 && (timestamp - today >= 0 || Math.floor(timer / 86400) <= 0)) { |
55 | | - tip = _this.$t('{n} 小时前', { n: Math.floor(timer / 3600) }) |
56 | | - } else if (timer / 86400 <= 31) { |
57 | | - tip = _this.$t('{n} 天前', { n: Math.floor(timer / 86400) }) |
| 60 | + let result = '' |
| 61 | + if (absDiff < 60) { |
| 62 | + // 1分钟内 |
| 63 | + result = _this.$t(`{n} 秒`, { n: Math.floor(absDiff) }) |
| 64 | + } else if (absDiff < 3600) { |
| 65 | + // 1小时内 |
| 66 | + result = _this.$t(`{n} 分钟`, { n: Math.floor(absDiff / 60) }) |
| 67 | + } else if (absDiff < 86400) { |
| 68 | + // 24小时内 |
| 69 | + result = _this.$t(`{n} 小时`, { n: Math.floor(absDiff / 3600) }) |
58 | 70 | } else { |
59 | | - tip = this.getLastDate(timestamp) |
| 71 | + // 10天内 |
| 72 | + result = _this.$t(`{n} 天`, { n: Math.floor(absDiff / 86400) }) |
60 | 73 | } |
61 | | - return tip |
| 74 | + // 未来时间加“后”,过去时间加“前” |
| 75 | + return isFuture ? `${result}${_this.$t('后')}` : `${result}${_this.$t('前')}` |
62 | 76 | }, |
63 | 77 | } |
64 | 78 |
|
|
0 commit comments