1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43 package org.eclipse.jgit.util;
44
45 import java.text.MessageFormat;
46 import java.util.Date;
47
48 import org.eclipse.jgit.internal.JGitText;
49
50
51
52
53
54 public class RelativeDateFormatter {
55 final static long SECOND_IN_MILLIS = 1000;
56
57 final static long MINUTE_IN_MILLIS = 60 * SECOND_IN_MILLIS;
58
59 final static long HOUR_IN_MILLIS = 60 * MINUTE_IN_MILLIS;
60
61 final static long DAY_IN_MILLIS = 24 * HOUR_IN_MILLIS;
62
63 final static long WEEK_IN_MILLIS = 7 * DAY_IN_MILLIS;
64
65 final static long MONTH_IN_MILLIS = 30 * DAY_IN_MILLIS;
66
67 final static long YEAR_IN_MILLIS = 365 * DAY_IN_MILLIS;
68
69
70
71
72
73
74
75 @SuppressWarnings("boxing")
76 public static String format(Date when) {
77
78 long ageMillis = SystemReader.getInstance().getCurrentTime()
79 - when.getTime();
80
81
82 if (ageMillis < 0)
83 return JGitText.get().inTheFuture;
84
85
86 if (ageMillis < upperLimit(MINUTE_IN_MILLIS))
87 return MessageFormat.format(JGitText.get().secondsAgo,
88 round(ageMillis, SECOND_IN_MILLIS));
89
90
91 if (ageMillis < upperLimit(HOUR_IN_MILLIS))
92 return MessageFormat.format(JGitText.get().minutesAgo,
93 round(ageMillis, MINUTE_IN_MILLIS));
94
95
96 if (ageMillis < upperLimit(DAY_IN_MILLIS))
97 return MessageFormat.format(JGitText.get().hoursAgo,
98 round(ageMillis, HOUR_IN_MILLIS));
99
100
101 if (ageMillis < 14 * DAY_IN_MILLIS)
102 return MessageFormat.format(JGitText.get().daysAgo,
103 round(ageMillis, DAY_IN_MILLIS));
104
105
106 if (ageMillis < 10 * WEEK_IN_MILLIS)
107 return MessageFormat.format(JGitText.get().weeksAgo,
108 round(ageMillis, WEEK_IN_MILLIS));
109
110
111 if (ageMillis < YEAR_IN_MILLIS)
112 return MessageFormat.format(JGitText.get().monthsAgo,
113 round(ageMillis, MONTH_IN_MILLIS));
114
115
116 if (ageMillis < 5 * YEAR_IN_MILLIS) {
117 long years = ageMillis / YEAR_IN_MILLIS;
118 String yearLabel = (years > 1) ? JGitText.get().years :
119 JGitText.get().year;
120 long months = round(ageMillis % YEAR_IN_MILLIS, MONTH_IN_MILLIS);
121 String monthLabel = (months > 1) ? JGitText.get().months :
122 (months == 1 ? JGitText.get().month : "");
123 return MessageFormat.format(
124 months == 0 ? JGitText.get().years0MonthsAgo : JGitText
125 .get().yearsMonthsAgo,
126 new Object[] { years, yearLabel, months, monthLabel });
127 }
128
129
130 return MessageFormat.format(JGitText.get().yearsAgo,
131 round(ageMillis, YEAR_IN_MILLIS));
132 }
133
134 private static long upperLimit(long unit) {
135 long limit = unit + unit / 2;
136 return limit;
137 }
138
139 private static long round(long n, long unit) {
140 long rounded = (n + unit / 2) / unit;
141 return rounded;
142 }
143 }