-
Notifications
You must be signed in to change notification settings - Fork 4
/
time.go
319 lines (304 loc) · 8.08 KB
/
time.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
package dads
import (
"fmt"
"strconv"
"strings"
"sync"
"time"
)
// DateCacheEntry - parse date cache entry
type DateCacheEntry struct {
Dt time.Time
DtInTz time.Time
TzOff float64
Valid bool
}
var (
parseDateCache = map[string]DateCacheEntry{}
parseDateCacheMtx *sync.RWMutex
)
// ProgressInfo display info about progress: i/n if current time >= last + period
// If displayed info, update last
func ProgressInfo(i, n int, start time.Time, last *time.Time, period time.Duration, msg string) {
now := time.Now()
if last.Add(period).Before(now) {
perc := 0.0
if n > 0 {
perc = (float64(i) * 100.0) / float64(n)
}
eta := start
if i > 0 && n > 0 {
etaNs := float64(now.Sub(start).Nanoseconds()) * (float64(n) / float64(i))
etaDuration := time.Duration(etaNs) * time.Nanosecond
eta = start.Add(etaDuration)
if msg != "" {
Printf("%d/%d (%.3f%%), ETA: %v: %s\n", i, n, perc, eta, msg)
} else {
Printf("%d/%d (%.3f%%), ETA: %v\n", i, n, perc, eta)
}
} else {
Printf("%s\n", msg)
}
*last = now
}
}
// ToYMDDate - return time formatted as YYYYMMDD
func ToYMDDate(dt time.Time) string {
return fmt.Sprintf("%04d%02d%02d", dt.Year(), dt.Month(), dt.Day())
}
// ToYMDHMDate - return time formatted as YYYY-MM-DD HH:MI
func ToYMDHMDate(dt time.Time) string {
return fmt.Sprintf("%04d-%02d-%02d %02d:%02d", dt.Year(), dt.Month(), dt.Day(), dt.Hour(), dt.Minute())
}
// ToYMDHMSDate - return time formatted as YYYY-MM-DD HH:MI:SS
func ToYMDHMSDate(dt time.Time) string {
return fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d", dt.Year(), dt.Month(), dt.Day(), dt.Hour(), dt.Minute(), dt.Second())
}
// ToESDate - return time formatted as YYYY-MM-DDTHH:MI:SS.uuuuuu+00:00
func ToESDate(dt time.Time) string {
return fmt.Sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%06.0f+00:00", dt.Year(), dt.Month(), dt.Day(), dt.Hour(), dt.Minute(), dt.Second(), float64(dt.Nanosecond())/1.0e3)
}
// ToYMDTHMSZDate - return time formatted as YYYY-MM-DDTHH:MI:SSZ
func ToYMDTHMSZDate(dt time.Time) string {
return fmt.Sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", dt.Year(), dt.Month(), dt.Day(), dt.Hour(), dt.Minute(), dt.Second())
}
// TimeParseAny - attempts to parse time from string YYYY-MM-DD HH:MI:SS
// Skipping parts from right until only YYYY id left
func TimeParseAny(dtStr string) (time.Time, error) {
formats := []string{
"2006-01-02T15:04:05.000000",
"2006-01-02T15:04:05.000",
"2006-01-02T15:04:05Z",
"2006-01-02 15:04:05",
"2006-01-02 15:04",
"2006-01-02 15",
"2006-01-02",
"2006-01",
"2006",
}
for _, format := range formats {
t, e := time.Parse(format, dtStr)
if e == nil {
return t, e
}
}
e := fmt.Errorf("Error:\nCannot parse date: '%v'", dtStr)
return time.Now(), e
}
// TimeParseESSec - parse datetime in ElasticSearch output format
func TimeParseESSec(dtStr string) (time.Time, error) {
ary := strings.Split(dtStr, "+")
ary2 := strings.Split(ary[0], ".")
return time.Parse("2006-01-02T15:04:05", ary2[0])
}
// TimeParseES - parse datetime in ElasticSearch output format
func TimeParseES(dtStr string) (time.Time, error) {
dtStr = strings.TrimSpace(strings.Replace(dtStr, "Z", "", -1))
ary := strings.Split(dtStr, "+")
ary2 := strings.Split(ary[0], ".")
var s string
if len(ary2) == 1 {
s = ary2[0] + ".000"
} else {
if len(ary2[1]) > 3 {
ary2[1] = ary2[1][:3]
}
s = strings.Join(ary2, ".")
}
return time.Parse("2006-01-02T15:04:05.000", s)
}
// TimeParseInterfaceString - parse interface{} -> string -> time.Time
func TimeParseInterfaceString(date interface{}) (dt time.Time, err error) {
sDate, ok := date.(string)
if !ok {
err = fmt.Errorf("%+v %T is not a string", date, date)
return
}
dt, err = TimeParseES(sDate)
return
}
// ParseDateWithTz - try to parse mbox date
func ParseDateWithTz(indt string) (dt, dtInTz time.Time, off float64, valid bool) {
k := strings.TrimSpace(indt)
if MT {
parseDateCacheMtx.RLock()
}
entry, ok := parseDateCache[k]
if MT {
parseDateCacheMtx.RUnlock()
}
if ok {
dt = entry.Dt
dtInTz = entry.DtInTz
off = entry.TzOff
valid = entry.Valid
return
}
defer func() {
defer func() {
entry := DateCacheEntry{Dt: dt, DtInTz: dtInTz, TzOff: off, Valid: valid}
if MT {
parseDateCacheMtx.Lock()
}
parseDateCache[k] = entry
if MT {
parseDateCacheMtx.Unlock()
}
}()
if !valid {
return
}
dtInTz = dt
ary := strings.Split(indt, "+0")
if len(ary) > 1 {
last := ary[len(ary)-1]
if TZOffsetRE.MatchString(last) {
digs := TZOffsetRE.ReplaceAllString(last, `$1`)
offH, _ := strconv.Atoi(digs[:1])
offM, _ := strconv.Atoi(digs[1:])
off = float64(offH) + float64(offM)/60.0
dt = dt.Add(time.Minute * time.Duration(off*-60))
return
}
}
ary = strings.Split(indt, "+1")
if len(ary) > 1 {
last := ary[len(ary)-1]
if TZOffsetRE.MatchString(last) {
digs := TZOffsetRE.ReplaceAllString(last, `$1`)
offH, _ := strconv.Atoi(digs[:1])
offM, _ := strconv.Atoi(digs[1:])
off = float64(10+offH) + float64(offM)/60.0
dt = dt.Add(time.Minute * time.Duration(off*-60))
return
}
}
ary = strings.Split(indt, "-0")
if len(ary) > 1 {
last := ary[len(ary)-1]
if TZOffsetRE.MatchString(last) {
digs := TZOffsetRE.ReplaceAllString(last, `$1`)
offH, _ := strconv.Atoi(digs[:1])
offM, _ := strconv.Atoi(digs[1:])
off = -(float64(offH) + float64(offM)/60.0)
dt = dt.Add(time.Minute * time.Duration(off*-60))
return
}
}
ary = strings.Split(indt, "-1")
if len(ary) > 1 {
last := ary[len(ary)-1]
if TZOffsetRE.MatchString(last) {
digs := TZOffsetRE.ReplaceAllString(last, `$1`)
offH, _ := strconv.Atoi(digs[:1])
offM, _ := strconv.Atoi(digs[1:])
off = -(float64(10+offH) + float64(offM)/60.0)
dt = dt.Add(time.Minute * time.Duration(off*-60))
return
}
}
}()
sdt := indt
// https://www.broobles.com/eml2mbox/mbox.html
// but the real world is not that simple
for _, r := range []string{">", ",", ")", "("} {
sdt = strings.Replace(sdt, r, "", -1)
}
for _, split := range []string{"+0", "+1", "."} {
ary := strings.Split(sdt, split)
sdt = ary[0]
}
for _, split := range []string{"-0", "-1"} {
ary := strings.Split(sdt, split)
lAry := len(ary)
if lAry > 1 {
_, err := strconv.Atoi(ary[lAry-1])
if err == nil {
sdt = strings.Join(ary[:lAry-1], split)
}
}
}
sdt = SpacesRE.ReplaceAllString(sdt, " ")
sdt = strings.ToLower(strings.TrimSpace(sdt))
ary := strings.Split(sdt, " ")
day := ary[0]
if len(day) > 3 {
day = day[:3]
}
_, ok = LowerDayNames[day]
if ok {
sdt = strings.Join(ary[1:], " ")
}
sdt = strings.TrimSpace(sdt)
for lm, m := range LowerFullMonthNames {
sdt = strings.Replace(sdt, lm, m, -1)
}
for lm, m := range LowerMonthNames {
sdt = strings.Replace(sdt, lm, m, -1)
}
ary = strings.Split(sdt, " ")
if len(ary) > 4 {
sdt = strings.Join(ary[:4], " ")
}
formats := []string{
"2006-01-02 15:04:05",
"2006-01-02t15:04:05",
"2006-01-02 15:04:05z",
"2006-01-02t15:04:05z",
"2 Jan 2006 15:04:05",
"02 Jan 2006 15:04:05",
"2 Jan 06 15:04:05",
"02 Jan 06 15:04:05",
"2 Jan 2006 15:04",
"02 Jan 2006 15:04",
"2 Jan 06 15:04",
"02 Jan 06 15:04",
"Jan 2 15:04:05 2006",
"Jan 02 15:04:05 2006",
"Jan 2 15:04:05 06",
"Jan 02 15:04:05 06",
"Jan 2 15:04 2006",
"Jan 02 15:04 2006",
"Jan 2 15:04 06",
"Jan 02 15:04 06",
}
var (
err error
errs []error
)
for _, format := range formats {
dt, err = time.Parse(format, sdt)
if err == nil {
// Printf("Parsed %v\n", dt)
valid = true
return
}
errs = append(errs, err)
}
Printf("ParseDateWithTz: errors: %+v\n", errs)
Printf("ParseDateWithTz: '%s' -> '%s', day: %s\n", indt, sdt, day)
return
}
// PeriodParse - tries to parse period
func PeriodParse(perStr string) (dur time.Duration, ok bool) {
idx := strings.Index(perStr, "[rate reset in ")
if idx == -1 {
return
}
rateStr := ""
_, err := fmt.Sscanf(perStr[idx:], "[rate reset in %s", &rateStr)
if err != nil || len(rateStr) < 2 {
return
}
rateStr = rateStr[0 : len(rateStr)-1]
if rateStr == "" {
return
}
d, err := time.ParseDuration(rateStr)
if err != nil {
return
}
dur = d
ok = true
return
}