/
timeago.go
327 lines (262 loc) · 7.56 KB
/
timeago.go
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// Copyright 2013 Simon HEGE. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
//timeago allows the formatting of time in terms of fuzzy timestamps.
//For example:
// one minute ago
// 3 years ago
// in 2 minutes
package timeago
import (
"fmt"
"strings"
"time"
)
const (
Day time.Duration = time.Hour * 24
Month time.Duration = Day * 30
Year time.Duration = Day * 365
)
type FormatPeriod struct {
D time.Duration
One string
Many string
}
//Config allows the customization of timeago.
//You may configure string items (language, plurals, ...) and
//maximum allowed duration value for fuzzy formatting.
type Config struct {
PastPrefix string
PastSuffix string
FuturePrefix string
FutureSuffix string
Periods []FormatPeriod
Zero string
Max time.Duration //Maximum duration for using the special formatting.
//DefaultLayout is used if delta is greater than the minimum of last period
//in Periods and Max. It is the desired representation of the date 2nd of
// January 2006.
DefaultLayout string
}
//Predefined english configuration
var English = Config{
PastPrefix: "",
PastSuffix: " ago",
FuturePrefix: "in ",
FutureSuffix: "",
Periods: []FormatPeriod{
{time.Second, "about a second", "%d seconds"},
{time.Minute, "about a minute", "%d minutes"},
{time.Hour, "about an hour", "%d hours"},
{Day, "one day", "%d days"},
{Month, "one month", "%d months"},
{Year, "one year", "%d years"},
},
Zero: "about a second",
Max: 73 * time.Hour,
DefaultLayout: "2006-01-02",
}
var Portuguese = Config{
PastPrefix: "há ",
PastSuffix: "",
FuturePrefix: "daqui a ",
FutureSuffix: "",
Periods: []FormatPeriod{
{time.Second, "um segundo", "%d segundos"},
{time.Minute, "um minuto", "%d minutos"},
{time.Hour, "uma hora", "%d horas"},
{Day, "um dia", "%d dias"},
{Month, "um mês", "%d meses"},
{Year, "um ano", "%d anos"},
},
Zero: "menos de um segundo",
Max: 73 * time.Hour,
DefaultLayout: "02-01-2006",
}
var Spanish = Config{
PastPrefix: "hace ",
PastSuffix: "",
FuturePrefix: "en ",
FutureSuffix: "",
Periods: []FormatPeriod{
{time.Second, "un segundo", "%d segundos"},
{time.Minute, "un minuto", "%d minutos"},
{time.Hour, "una hora", "%d horas"},
{Day, "un día", "%d días"},
{Month, "un mes", "%d meses"},
{Year, "un año", "%d años"},
},
Zero: "menos de un segundo",
Max: 73 * time.Hour,
DefaultLayout: "02-01-2006",
}
var Chinese = Config{
PastPrefix: "",
PastSuffix: "前",
FuturePrefix: "于 ",
FutureSuffix: "",
Periods: []FormatPeriod{
{time.Second, "1 秒", "%d 秒"},
{time.Minute, "1 分钟", "%d 分钟"},
{time.Hour, "1 小时", "%d 小时"},
{Day, "1 天", "%d 天"},
{Month, "1 月", "%d 月"},
{Year, "1 年", "%d 年"},
},
Zero: "1 秒",
Max: 73 * time.Hour,
DefaultLayout: "2006-01-02",
}
//Predefined french configuration
var French = Config{
PastPrefix: "il y a ",
PastSuffix: "",
FuturePrefix: "dans ",
FutureSuffix: "",
Periods: []FormatPeriod{
{time.Second, "environ une seconde", "moins d'une minute"},
{time.Minute, "environ une minute", "%d minutes"},
{time.Hour, "environ une heure", "%d heures"},
{Day, "un jour", "%d jours"},
{Month, "un mois", "%d mois"},
{Year, "un an", "%d ans"},
},
Zero: "environ une seconde",
Max: 73 * time.Hour,
DefaultLayout: "02/01/2006",
}
//Predefined german configuration
var German = Config{
PastPrefix: "vor ",
PastSuffix: "",
FuturePrefix: "in ",
FutureSuffix: "",
Periods: []FormatPeriod{
{time.Second, "einer Sekunde", "%d Sekunden"},
{time.Minute, "einer Minute", "%d Minuten"},
{time.Hour, "einer Stunde", "%d Stunden"},
{Day, "einem Tag", "%d Tagen"},
{Month, "einem Monat", "%d Monaten"},
{Year, "einem Jahr", "%d Jahren"},
},
Zero: "einer Sekunde",
Max: 73 * time.Hour,
DefaultLayout: "02.01.2006",
}
//Predefined turkish configuration
var Turkish = Config{
PastPrefix: "",
PastSuffix: " önce",
FuturePrefix: "",
FutureSuffix: " içinde",
Periods: []FormatPeriod{
{time.Second, "yaklaşık bir saniye", "%d saniye"},
{time.Minute, "yaklaşık bir dakika", "%d dakika"},
{time.Hour, "yaklaşık bir saat", "%d saat"},
{Day, "bir gün", "%d gün"},
{Month, "bir ay", "%d ay"},
{Year, "bir yıl", "%d yıl"},
},
Zero: "yaklaşık bir saniye",
Max: 73 * time.Hour,
DefaultLayout: "02/01/2006",
}
// Korean support
var Korean = Config{
PastPrefix: "",
PastSuffix: " 전",
FuturePrefix: "",
FutureSuffix: " 후",
Periods: []FormatPeriod{
{time.Second, "약 1초", "%d초"},
{time.Minute, "약 1분", "%d분"},
{time.Hour, "약 한시간", "%d시간"},
{Day, "하루", "%d일"},
{Month, "1개월", "%d개월"},
{Year, "1년", "%d년"},
},
Zero: "방금",
Max: 10 * 365 * 24 * time.Hour,
DefaultLayout: "2006-01-02",
}
//Format returns a textual representation of the time value formatted according to the layout
//defined in the Config. The time is compared to time.Now() and is then formatted as a fuzzy
//timestamp (eg. "4 days ago")
func (cfg Config) Format(t time.Time) string {
return cfg.FormatReference(t, time.Now())
}
//FormatReference is the same as Format, but the reference has to be defined by the caller
func (cfg Config) FormatReference(t time.Time, reference time.Time) string {
d := reference.Sub(t)
if (d >= 0 && d >= cfg.Max) || (d < 0 && -d >= cfg.Max) {
return t.Format(cfg.DefaultLayout)
}
return cfg.FormatRelativeDuration(d)
}
//FormatRelativeDuration is the same as Format, but for time.Duration.
//Config.Max is not used in this function, as there is no other alternative.
func (cfg Config) FormatRelativeDuration(d time.Duration) string {
isPast := d >= 0
if d < 0 {
d = -d
}
s, _ := cfg.getTimeText(d, true)
if isPast {
return strings.Join([]string{cfg.PastPrefix, s, cfg.PastSuffix}, "")
} else {
return strings.Join([]string{cfg.FuturePrefix, s, cfg.FutureSuffix}, "")
}
}
//Round the duration d in terms of step.
func round(d time.Duration, step time.Duration, roundCloser bool) time.Duration {
if roundCloser {
return time.Duration(float64(d)/float64(step) + 0.5)
}
return time.Duration(float64(d) / float64(step))
}
//Count the number of parameters in a format string
func nbParamInFormat(f string) int {
return strings.Count(f, "%") - 2*strings.Count(f, "%%")
}
//Convert a duration to a text, based on the current config
func (cfg Config) getTimeText(d time.Duration, roundCloser bool) (string, time.Duration) {
if len(cfg.Periods) == 0 || d < cfg.Periods[0].D {
return cfg.Zero, 0
}
for i, p := range cfg.Periods {
next := p.D
if i+1 < len(cfg.Periods) {
next = cfg.Periods[i+1].D
}
if i+1 == len(cfg.Periods) || d < next {
r := round(d, p.D, roundCloser)
if next != p.D && r == round(next, p.D, roundCloser) {
continue
}
if r == 0 {
return "", d
}
layout := p.Many
if r == 1 {
layout = p.One
}
if nbParamInFormat(layout) == 0 {
return layout, d - r*p.D
}
return fmt.Sprintf(layout, r), d - r*p.D
}
}
return d.String(), 0
}
//NoMax creates an new config without a maximum
func NoMax(cfg Config) Config {
return WithMax(cfg, 9223372036854775807, time.RFC3339)
}
//WithMax creates an new config with special formatting limited to durations less than max.
//Values greater than max will be formatted by the standard time package using the defaultLayout.
func WithMax(cfg Config, max time.Duration, defaultLayout string) Config {
n := cfg
n.Max = max
n.DefaultLayout = defaultLayout
return n
}