-
Notifications
You must be signed in to change notification settings - Fork 0
/
date.go
605 lines (545 loc) · 13.2 KB
/
date.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
package g
import (
"context"
"errors"
"fmt"
"runtime"
"strings"
"sync"
"time"
)
var (
// The dataTimeFormats is predefined layouts for use
// in DateToString, DateToStrings and StringToDate functions.
// Each element shows by example the formatting of an element of
// the reference time. Only these values are recognized.
// Text in the layout string that is not recognized as part of the
// reference time is echoed verbatim during Format and expected to appear
// verbatim in the input to Parse.
//
// Year: "2006" "06"
// Month: "Jan" "January" "01" "1"
// Day of the week: "Mon" "Monday"
// Day of the month: "2" "_2" "02"
// Day of the year: "__2" "002"
// Hour: "15" "3" "03" (PM or AM)
// Minute: "4" "04"
// Second: "5" "05"
// AM/PM mark: "PM"
//
// Numeric time zone offsets format as follows:
//
// "-0700" ±hhmm
// "-07:00" ±hh:mm
// "-07" ±hh
// "-070000" ±hhmmss
// "-07:00:00" ±hh:mm:ss
//
// Replacing the sign in the format with a Z triggers
// the ISO 8601 behavior of printing Z instead of an
// offset for the UTC zone. Thus:
//
// "Z0700" Z or ±hhmm
// "Z07:00" Z or ±hh:mm
// "Z07" Z or ±hh
// "Z070000" Z or ±hhmmss
// "Z07:00:00" Z or ±hh:mm:ss
dataTimeFormats = []string{
time.Layout,
time.ANSIC,
time.UnixDate,
time.RubyDate,
time.RFC822,
time.RFC822Z,
time.RFC850,
time.RFC1123,
time.RFC1123Z,
time.RFC3339,
time.RFC3339Nano,
time.Kitchen,
time.Stamp,
time.StampMilli,
time.StampMicro,
time.StampNano,
time.DateTime,
time.DateOnly,
time.TimeOnly,
"15:04", // short time: hours and minutes
"2.1.06",
"2.1.2006",
"2.01.06",
"2.01.2006",
"02.01.2006",
"02.1.06",
"02.1.2006",
"2.1.06 15:04",
"2.1.2006 15:04",
"2.01.06 15:04",
"2.01.2006 15:04",
"02.01.2006 15:04",
"02.1.06 15:04",
"02.1.2006 15:04",
"2.1.06 15:04:05",
"2.1.2006 15:04:05",
"2.01.06 15:04:05",
"2.01.2006 15:04:05",
"02.01.2006 15:04:05",
"02.1.06 15:04:05",
"02.1.2006 15:04:05",
"2/1/06",
"2/1/2006",
"2/01/06",
"2/01/2006",
"02/01/2006",
"02/1/06",
"02/1/2006",
"2/1/06 15:04",
"2/1/2006 15:04",
"2/01/06 15:04",
"2/01/2006 15:04",
"02/01/2006 15:04",
"02/1/06 15:04",
"02/1/2006 15:04",
"2/1/06 15:04:05",
"2/1/2006 15:04:05",
"2/01/06 15:04:05",
"2/01/2006 15:04:05",
"02/01/2006 15:04:05",
"02/1/06 15:04:05",
"02/1/2006 15:04:05",
"2-1-06",
"2-1-2006",
"2-01-06",
"2-01-2006",
"02-01-2006",
"02-1-06",
"02-1-2006",
"2-1-06 15:04",
"2-1-2006 15:04",
"2-01-06 15:04",
"2-01-2006 15:04",
"02-01-2006 15:04",
"02-1-06 15:04",
"02-1-2006 15:04",
"2-1-06 15:04:05",
"2-1-2006 15:04:05",
"2-01-06 15:04:05",
"2-01-2006 15:04:05",
"02-01-2006 15:04:05",
"02-1-06 15:04:05",
"02-1-2006 15:04:05",
"06/2/1",
"2006/2/1",
"06/2/01",
"2006/2/01",
"2006/02/01",
"06/02/1",
"2006/02/1",
"06/2/1 15:04",
"2006/2/1 15:04",
"06/2/01 15:04",
"2006/2/01 15:04",
"2006/02/01 15:04",
"06/02/1 15:04",
"2006/02/1 15:04",
"06/2/1 15:04:05",
"2006/2/1 15:04:05",
"06/2/01 15:04:05",
"2006/2/01 15:04:05",
"2006/02/01 15:04:05",
"06/02/1 15:04:05",
"2006/02/1 15:04:05",
"06-2-1",
"2006-2-1",
"06-2-01",
"2006-2-01",
"2006-02-01",
"06-02-1",
"2006-02-1",
"06-2-1 15:04",
"2006-2-1 15:04",
"06-2-01 15:04",
"2006-2-01 15:04",
"2006-02-01 15:04",
"06-02-1 15:04",
"2006-02-1 15:04",
"06-2-1 15:04:05",
"2006-2-1 15:04:05",
"06-2-01 15:04:05",
"2006-2-01 15:04:05",
"2006-02-01 15:04:05",
"06-02-1 15:04:05",
"2006-02-1 15:04:05",
"06/1/2",
"2006/1/2",
"06/01/2",
"2006/01/2",
"2006/01/02",
"06/1/02",
"2006/1/02",
"06/1/2 15:04",
"2006/1/2 15:04",
"06/01/2 15:04",
"2006/01/2 15:04",
"2006/01/02 15:04",
"06/1/02 15:04",
"2006/1/02 15:04",
"06/1/2 15:04:05",
"2006/1/2 15:04:05",
"06/01/2 15:04:05",
"2006/01/2 15:04:05",
"2006/01/02 15:04:05",
"06/1/02 15:04:05",
"2006/1/02 15:04:05",
"06-1-2",
"2006-1-2",
"06-01-2",
"2006-01-2",
"06-1-02",
"2006-1-02",
"06-1-2 15:04",
"2006-1-2 15:04",
"06-01-2 15:04",
"2006-01-2 15:04",
"2006-01-02 15:04",
"06-1-02 15:04",
"2006-1-02 15:04",
"06-1-2 15:04:05",
"2006-1-2 15:04:05",
"06-01-2 15:04:05",
"2006-01-2 15:04:05",
"06-1-02 15:04:05",
"2006-1-02 15:04:05",
}
// The pythonToGolangFormats maps Python date format specifiers
// to GoLang date format specifiers.
//
// Note that Python specifiers such as %U and %W have no
// counterparts in GoLang.
pythonToGolangFormats = map[string]string{
"%d": "02",
"%m": "01",
"%Y": "2006",
"%H": "15",
"%M": "04",
"%S": "05",
"%a": "Mon",
"%A": "Monday",
"%w": "0",
"%b": "Jan",
"%B": "January",
"%y": "06",
"%I": "03",
"%p": "PM",
"%f": ".999999",
"%z": "-0700",
"%Z": "MST",
"%j": "002",
//"%U": "00", // ignored
//"%W": "00", // ignored
"%c": "Mon Jan 2 15:04:05 2006",
"%x": "01/02/06",
"%X": "15:04:05",
"%%": "%",
}
)
// dateParseError stores information about a date parsing error.
type dateParseError struct {
layout string
err error
}
// dateFoundValue is a thread-safe value that indicates
// whether a date was found in a string.
type dateFoundValue struct {
m sync.Mutex
found bool
value time.Time
}
// SetValue sets a new value for the found object. It locks the Mutex
// before changing the value and unlocks it after the change is complete.
func (f *dateFoundValue) SetValue(found bool, value time.Time) {
f.m.Lock()
defer f.m.Unlock()
f.value = value
f.found = found
}
// GetValue retrieves the current value of the Found. It locks the Mutex
// before reading the value and unlocks it after the read is complete.
func (f *dateFoundValue) GetValue() (time.Time, error) {
f.m.Lock()
defer f.m.Unlock()
if f.found {
return f.value, nil
}
return time.Time{}, errors.New("date and time could not be recognized")
}
// The pythonToGolangFormat converts a Python date format specifier to a
// GoLang date format specifier.
func pythonToGolangFormat(format string) string {
builder := &strings.Builder{}
i := 0
for i < len(format) {
replaced := false
for k, v := range pythonToGolangFormats {
if strings.HasPrefix(format[i:], k) {
builder.WriteString(v)
i += len(k)
replaced = true
break
}
}
if !replaced {
builder.WriteByte(format[i])
i++
}
}
return builder.String()
}
// StringToDate converts a string to a time.Time object using the provided
// formats. If no format is given, it uses default date-time formats.
//
// This function leverages goroutines to parse the string concurrently
// using different formats. When the first successful parsing occurs,
// the function stops all other goroutines and returns the result.
// If no parsing is successful, the function returns an error.
//
// Example usage:
//
// // Automatic pattern detection.
// t, err := StringToDate("2006-01-02")
// if err != nil {
// log.Fatal(err)
// }
// fmt.Println(t)
//
// t, err = StringToDate("2006/01/02 15:04:05")
// if err != nil {
// log.Fatal(err)
// }
// fmt.Println(t)
//
// // Using custom formats as Python.
// t, err = StringToDate("Jan 02, 2006", "%b %d, %Y")
// if err != nil {
// log.Fatal(err)
// }
// fmt.Println(t)
//
// // Using Go's date formatting
// t, err = StringToDate("Jan 02, 2006", "Jan 02, 2006")
// if err != nil {
// log.Fatal(err)
// }
// fmt.Println(t)
func StringToDate(s string, patterns ...string) (time.Time, error) {
var (
formats []string
wg sync.WaitGroup
)
for _, pattern := range patterns {
if strings.Contains(pattern, "%") {
formats = append(formats, pythonToGolangFormat(pattern))
} else {
formats = append(formats, pattern)
}
}
if len(formats) == 0 {
formats = dataTimeFormats
}
errorChan := make(chan dateParseError, len(formats))
resultChan := make(chan time.Time, 1)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sem := make(chan struct{}, runtime.GOMAXPROCS(0)) // limit goroutines
for _, format := range formats {
wg.Add(1)
sem <- struct{}{} // acquire a spot in the semaphore
go func(layout string) {
defer wg.Done()
defer func() { <-sem }() // release the spot in the semaphore
select {
case <-ctx.Done():
return
default:
if t, err := time.Parse(layout, s); err == nil {
select {
case resultChan <- t:
default:
}
cancel()
} else {
errorChan <- dateParseError{layout, err}
}
}
}(format)
}
// Close the error channel when all goroutines are done.
go func() {
wg.Wait()
close(errorChan)
}()
// Get result from channels.
var errorsList []error
for {
select {
case t := <-resultChan:
return t, nil
case parseErr, ok := <-errorChan:
if ok {
errorsList = append(
errorsList,
fmt.Errorf("format %s: %w", parseErr.layout, parseErr.err),
)
} else {
// If the channel is closed and there are no more errors.
if len(errorsList) > 0 {
return time.Time{}, fmt.Errorf(
"failed to parse date: %v",
errorsList,
)
}
return time.Time{}, fmt.Errorf("failed to parse date")
}
}
}
}
// DateToString converts a Date to a string based on the provided format.
//
// If multiple formats are provided, only the first one will be processed.
//
// Example usage:
//
// date := time.Date(2023, 7, 17, 0, 0, 0, 0, time.UTC)
// s, err := DateToString(date, "2006-01-02")
// if err != nil {
// log.Fatal(err)
// }
// fmt.Println(s) // Output: "2023-07-17"
func DateToString(t time.Time, patterns ...string) (string, error) {
var formats []string
if len(patterns) != 0 {
formats = append(formats, patterns[0]) // first only value
}
s, err := DateToStrings(t, formats...)
if err != nil {
return "", err
}
return s[0], nil
}
// DateToStrings converts a Time object into string(s) using the
// provided formats. The function uses time.DateTime format as a default
// option if no format is provided. In case the pattern includes
// a percentage ("%") character, it converts Python strftime format
// to Go's time format before applying it.
//
// It returns an array of the results and an error if there was
// a problem with the formatting.
//
// Example usage:
//
// t := time.Now()
// patterns := []string{"%Y-%m-%d", "02 Jan 06", time.RFC3339}
// results, err := DateToStrings(t, patterns...)
//
// if err != nil {
// log.Fatal(err)
// return
// }
//
// for i, str := range results {
// fmt.Printf("Date in format %s: %s\n", patterns[i], str)
// }
func DateToStrings(t time.Time, patterns ...string) ([]string, error) {
var (
formats []string
results []string
)
for _, pattern := range patterns {
if strings.Contains(pattern, "%") {
formats = append(formats, pythonToGolangFormat(pattern))
} else {
formats = append(formats, pattern)
}
}
if len(formats) == 0 {
// Use the format from the system locale.
formats = append(formats, time.DateTime)
}
for _, format := range formats {
// Format does not return an error if the formatting data is written
// incorrectly. It just leaves the unrecognized fragment as is.
s := t.Format(format)
// The only way to check the correct format - reconstruction of time.
t2, err := time.Parse(format, s)
if err != nil || t != t2 {
return []string{}, errors.New("invalid format")
}
results = append(results, s)
}
return results, nil
}
// ChangeTimeZone returns a time where the hour and minute are the same
// as the input time, but the time zone is changed. This can be used to
// convert a local time to a different time zone while keeping the "clock
// time" the same.
//
// Example usage:
//
// t, _ := time.Parse(time.RFC3339, "2023-06-17T08:15:45Z")
// newTime, err := ChangeTimeZone(t, "America/New_York")
// if err != nil {
// log.Fatal(err)
// }
// fmt.Println(newTime)
// // Output: 2023-06-17 08:15:45 -0400 EDT
func ChangeTimeZone(t time.Time, timezone string) (time.Time, error) {
loc, err := time.LoadLocation(timezone)
if err != nil {
return time.Time{}, err
}
return time.Date(
t.Year(),
t.Month(),
t.Day(),
t.Hour(),
t.Minute(),
t.Second(),
t.Nanosecond(),
loc,
), nil
}
// SetTimeZone changes the time zone, and changes the local time
// according to the new time zone. This can be used to convert the time from
// one time zone to another. The time value will adjust to maintain the same
// moment in time, but the hour, minute, and second may change.
//
// Example usage:
//
// t, _ := time.Parse(time.RFC3339, "2023-06-17T08:15:45Z")
// newTime, err := SetTimeZone(t, "America/New_York")
// if err != nil {
// log.Fatal(err)
// }
// fmt.Println(newTime)
// // Output: 2023-06-17 04:15:45 -0400 EDT
func SetTimeZone(t time.Time, timezone string) (time.Time, error) {
loc, err := time.LoadLocation(timezone)
if err != nil {
return time.Time{}, err
}
return t.In(loc), nil
}
// MoveTimeZone adds or subtracts multiple time zones from a given time.
// The function uses the time.Duration type to add/subtract hours from
// the current time. Positive 'tz' values move the time forward, and
// negative values move it backward.
//
// Example usage:
//
// t := time.Now()
// newTime := MoveTimeZone(t, -3)
// fmt.Println(newTime)
// // Output: <current time minus 3 hours>
func MoveTimeZone(t time.Time, tz int) time.Time {
return t.Add(time.Duration(tz) * time.Hour)
}