itcast-relative-time 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +34 -2
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
import dayjs from "dayjs";
|
|
2
|
-
export function formatRelativeTime() {
|
|
2
|
+
export function formatRelativeTime(time) {
|
|
3
|
+
let targetTime;
|
|
4
|
+
if (time instanceof Date) {
|
|
5
|
+
targetTime = time.getTime();
|
|
6
|
+
} else if (typeof time === "number") {
|
|
7
|
+
targetTime = time.toString().length === 10 ? time * 1000 : time;
|
|
8
|
+
} else {
|
|
9
|
+
throw new Error("参数错误:请传入有效的Date对象或时间戳(数字类型)");
|
|
10
|
+
}
|
|
3
11
|
const now = dayjs();
|
|
4
|
-
|
|
12
|
+
const target = dayjs(targetTime);
|
|
13
|
+
const diffSecond = now.diff(target, "second");
|
|
14
|
+
const rules = [
|
|
15
|
+
{ threshold: 10, text: "刚刚" },
|
|
16
|
+
{ threshold: 60, text: (diff) => `${Math.floor(diff)}秒前` },
|
|
17
|
+
{ threshold: 3600, text: (diff) => `${Math.floor(diff / 60)}分钟前` },
|
|
18
|
+
{ threshold: 86400, text: (diff) => `${Math.floor(diff / 3600)}小时前` },
|
|
19
|
+
{ threshold: 2592000, text: (diff) => `${Math.floor(diff / 86400)}天前` },
|
|
20
|
+
{
|
|
21
|
+
threshold: 31536000,
|
|
22
|
+
text: (diff) => `${Math.floor(diff / 2592000)}个月前`,
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
threshold: Infinity,
|
|
26
|
+
text: (diff) => `${Math.floor(diff / 31536000)}年前`,
|
|
27
|
+
},
|
|
28
|
+
];
|
|
29
|
+
for (const rule of rules) {
|
|
30
|
+
if (diffSecond < rule.threshold) {
|
|
31
|
+
return typeof rule.text === "function"
|
|
32
|
+
? rule.text(diffSecond)
|
|
33
|
+
: rule.text;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return target.format("YYYY-MM-DD HH:mm");
|
|
5
37
|
}
|
|
6
38
|
export default formatRelativeTime;
|