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
76
77
78
79 @SuppressWarnings("boxing")
80 public static String format(Date when) {
81
82 long ageMillis = SystemReader.getInstance().getCurrentTime()
83 - when.getTime();
84
85
86 if (ageMillis < 0)
87 return JGitText.get().inTheFuture;
88
89
90 if (ageMillis < upperLimit(MINUTE_IN_MILLIS))
91 return MessageFormat.format(JGitText.get().secondsAgo,
92 round(ageMillis, SECOND_IN_MILLIS));
93
94
95 if (ageMillis < upperLimit(HOUR_IN_MILLIS))
96 return MessageFormat.format(JGitText.get().minutesAgo,
97 round(ageMillis, MINUTE_IN_MILLIS));
98
99
100 if (ageMillis < upperLimit(DAY_IN_MILLIS))
101 return MessageFormat.format(JGitText.get().hoursAgo,
102 round(ageMillis, HOUR_IN_MILLIS));
103
104
105 if (ageMillis < 14 * DAY_IN_MILLIS)
106 return MessageFormat.format(JGitText.get().daysAgo,
107 round(ageMillis, DAY_IN_MILLIS));
108
109
110 if (ageMillis < 10 * WEEK_IN_MILLIS)
111 return MessageFormat.format(JGitText.get().weeksAgo,
112 round(ageMillis, WEEK_IN_MILLIS));
113
114
115 if (ageMillis < YEAR_IN_MILLIS)
116 return MessageFormat.format(JGitText.get().monthsAgo,
117 round(ageMillis, MONTH_IN_MILLIS));
118
119
120 if (ageMillis < 5 * YEAR_IN_MILLIS) {
121 long years = round(ageMillis, MONTH_IN_MILLIS) / 12;
122 String yearLabel = (years > 1) ? JGitText.get().years :
123 JGitText.get().year;
124 long months = round(ageMillis - years * YEAR_IN_MILLIS,
125 MONTH_IN_MILLIS);
126 String monthLabel = (months > 1) ? JGitText.get().months :
127 (months == 1 ? JGitText.get().month : "");
128 return MessageFormat.format(
129 months == 0 ? JGitText.get().years0MonthsAgo : JGitText
130 .get().yearsMonthsAgo,
131 new Object[] { years, yearLabel, months, monthLabel });
132 }
133
134
135 return MessageFormat.format(JGitText.get().yearsAgo,
136 round(ageMillis, YEAR_IN_MILLIS));
137 }
138
139 private static long upperLimit(long unit) {
140 long limit = unit + unit / 2;
141 return limit;
142 }
143
144 private static long round(long n, long unit) {
145 long rounded = (n + unit / 2) / unit;
146 return rounded;
147 }
148 }