-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtimeago.go
298 lines (238 loc) · 6.22 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
package timeago
import (
"math"
"strconv"
"strings"
"time"
"github.com/SerhiiCho/timeago/v3/internal/utils"
)
var (
// cachedJsonRes saves parsed JSON translations to prevent
// parsing the same JSON file multiple times.
cachedJsonRes = map[string]*LangSet{}
// options is a list of options that modify the final output.
// Some options are noSuffix, upcoming, online, and justNow.
options = []opt{}
// conf is configuration provided by the user.
conf = defaultConfig()
// langSet is a pointer to the current language set that
// is currently being used.
langSet *LangSet
)
type timeNumbers struct {
Seconds int
Minutes int
Hours int
Days int
Weeks int
Months int
Years int
}
// Parse coverts privided datetime into `x time ago` format.
// The first argument can have 3 types:
// 1. int (Unix timestamp)
// 2. time.Time (Type from Go time package)
// 3. string (Datetime string in format 'YYYY-MM-DD HH:MM:SS')
func Parse(date interface{}, opts ...opt) (string, error) {
options = []opt{}
langSet = nil
var t time.Time
var err error
switch userDate := date.(type) {
case int:
t = unixToTime(userDate)
case string:
t, err = strToTime(userDate)
default:
t = date.(time.Time)
}
if err != nil {
return "", err
}
enableOptions(opts)
return computeTimeSince(t)
}
// Configure applies the given configuration to the timeago without
// overriding the previous configuration. It will only override the
// provided configuration. If you want to override the previous
// configurations, use Reconfigure function instead.
func Configure(c Config) {
if c.OnlineThreshold > 0 {
conf.OnlineThreshold = c.OnlineThreshold
}
if c.JustNowThreshold > 0 {
conf.JustNowThreshold = c.JustNowThreshold
}
if c.Language != "" {
conf.Language = c.Language
}
if c.Location != "" {
conf.Location = c.Location
}
if len(c.Translations) > 0 {
conf.Translations = c.Translations
}
}
// Reconfigure reconfigures the timeago with the provided configuration.
// It will override the previous configuration with the new one.
func Reconfigure(c Config) {
conf = defaultConfig()
cachedJsonRes = map[string]*LangSet{}
Configure(c)
}
func defaultConfig() *Config {
return NewConfig("en", "UTC", []LangSet{}, 60, 60)
}
func strToTime(userDate string) (time.Time, error) {
if !conf.isLocationProvided() {
parsedTime, _ := time.Parse(time.DateTime, userDate)
return parsedTime, nil
}
loc, err := location()
if err != nil {
return time.Time{}, err
}
parsedTime, err := time.ParseInLocation(time.DateTime, userDate, loc)
if err != nil {
return time.Time{}, utils.Errorf("%v", err)
}
return parsedTime, nil
}
// location loads location from the time package
func location() (*time.Location, error) {
if !conf.isLocationProvided() {
return time.Now().Location(), nil
}
loc, err := time.LoadLocation(conf.Location)
if err != nil {
return nil, utils.Errorf("%v", err)
}
return loc, nil
}
func computeTimeSince(t time.Time) (string, error) {
now := time.Now()
var err error
// Adjust times based on location if provided
if t, now, err = adjustTimesForLocation(t, now); err != nil {
return "", err
}
timeInSec := computeTimeDifference(t, now)
if langSet, err = newLangSet(); err != nil {
return "", err
}
if optionIsEnabled(OptOnline) && timeInSec < conf.OnlineThreshold {
return langSet.Online, nil
}
if optionIsEnabled(OptJustNow) && timeInSec < conf.JustNowThreshold {
return langSet.JustNow, nil
}
var timeUnit string
langForms, timeNum := findLangForms(timeInSec)
if timeUnit, err = computeTimeUnit(langForms, timeNum); err != nil {
return "", err
}
suffix := computeSuffix()
return mergeFinalOutput(timeNum, timeUnit, suffix)
}
// adjustTimesForLocation adjusts the given times based on the provided location.
func adjustTimesForLocation(t, now time.Time) (time.Time, time.Time, error) {
if !conf.isLocationProvided() {
return t, now, nil
}
loc, err := location()
if err != nil {
return t, now, err
}
return t.In(loc), now.In(loc), nil
}
// computeTimeDifference returns the absolute time difference in seconds.
func computeTimeDifference(t, now time.Time) int {
timeInSec := int(now.Sub(t).Seconds())
if timeInSec < 0 {
enableOption(OptUpcoming)
return -timeInSec
}
return timeInSec
}
func mergeFinalOutput(timeNum int, timeUnit, suffix string) (string, error) {
replacer := strings.NewReplacer(
"{timeUnit}", timeUnit,
"{num}", strconv.Itoa(timeNum),
"{ago}", suffix,
)
out := replacer.Replace(langSet.Format)
return strings.TrimSpace(out), nil
}
func findLangForms(timeInSec int) (LangForms, int) {
nums := calculateTimeNumbers(float64(timeInSec))
switch {
case timeInSec < 60:
return langSet.Second, nums.Seconds
case nums.Minutes < 60:
return langSet.Minute, nums.Minutes
case nums.Hours < 24:
return langSet.Hour, nums.Hours
case nums.Days < 7:
return langSet.Day, nums.Days
case nums.Weeks < 4:
return langSet.Week, nums.Weeks
case nums.Months < 12:
if nums.Months == 0 {
nums.Months = 1
}
return langSet.Month, nums.Months
}
return langSet.Year, nums.Years
}
func computeSuffix() string {
if optionIsEnabled(OptNoSuffix) || optionIsEnabled(OptUpcoming) {
return ""
}
return langSet.Ago
}
func calculateTimeNumbers(seconds float64) timeNumbers {
minutes := math.Round(seconds / 60)
hours := math.Round(seconds / 3600)
days := math.Round(seconds / 86400)
weeks := math.Round(seconds / 604800)
months := math.Round(seconds / 2629440)
years := math.Round(seconds / 31553280)
return timeNumbers{
Seconds: int(seconds),
Minutes: int(minutes),
Hours: int(hours),
Days: int(days),
Weeks: int(weeks),
Months: int(months),
Years: int(years),
}
}
func computeTimeUnit(langForm LangForms, num int) (string, error) {
form, err := timeUnitForm(num)
if err != nil {
return "", err
}
if unit, ok := langForm[form]; ok {
return unit, nil
}
return langForm["other"], nil
}
func timeUnitForm(num int) (string, error) {
rule, err := identifyGrammarRules(num, conf.Language)
if err != nil {
return "", err
}
switch {
case rule.Zero:
return "zero", nil
case rule.One:
return "one", nil
case rule.Few:
return "few", nil
case rule.Two:
return "two", nil
case rule.Many:
return "many", nil
}
return "other", nil
}