回答編集履歴

1

相対日付計算を追加

2019/05/01 23:36

投稿

naomi3
naomi3

スコア1105

test CHANGED
@@ -13,3 +13,61 @@
13
13
  console.log(dateString);
14
14
 
15
15
  ```
16
+
17
+ ・~秒前、~分前の値は切り捨てです。
18
+
19
+ ・1か月を一律(365.25 / 12)日とみなして計算しています。
20
+
21
+ ・未来の値は考慮していません。
22
+
23
+ ```JavaScipt
24
+
25
+ function toRelativeDate(ux) {
26
+
27
+ var date = new Date(parseInt(ux, 10));
28
+
29
+ var seconds = (new Date - date) / 1000;
30
+
31
+ var days = seconds / 3600 / 24;
32
+
33
+
34
+
35
+ if (seconds < 1) return '今';
36
+
37
+ if (seconds < 60) return Math.floor(seconds) + '秒前';
38
+
39
+ if (seconds < 3600) return Math.floor(seconds / 60) + '分前';
40
+
41
+ if (seconds < 3600 * 24) return Math.floor(seconds / 3600) + '時間前';
42
+
43
+ if (days < 365.25 / 12) return Math.floor(days) + '日前';
44
+
45
+ // 1か月を一律(365.25 / 12)日とみなして計算
46
+
47
+ if (days < 365.25) return Math.floor(days / 365.25 * 12) + 'か月前';
48
+
49
+ return date.getFullYear() + '年' + (date.getMonth() + 1) + '月' + date.getDate() + '日';
50
+
51
+ }
52
+
53
+
54
+
55
+ // テスト
56
+
57
+
58
+
59
+ console.log(toRelativeDate((new Date().valueOf() - 500).toString()));
60
+
61
+ console.log(toRelativeDate((new Date().valueOf() - 12700).toString()));
62
+
63
+ console.log(toRelativeDate((new Date().valueOf() - 34.5 * 60000).toString()));
64
+
65
+ console.log(toRelativeDate((new Date().valueOf() - 23.6 * 3600000).toString()));
66
+
67
+ console.log(toRelativeDate((new Date().valueOf() - 21.5 * 24 * 3600000).toString()));
68
+
69
+ console.log(toRelativeDate((new Date().valueOf() - 360 * 24 * 3600000).toString()));
70
+
71
+ console.log(toRelativeDate(new Date(2018, 5-1, 1).valueOf().toString()));
72
+
73
+ ```