-
Notifications
You must be signed in to change notification settings - Fork 0
/
date.go
81 lines (67 loc) · 2.83 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
package main
import (
"regexp"
"time"
)
type Pattern struct {
regex *regexp.Regexp
pattern string
}
func ParseDateTime(input string) (time.Time, error) {
var patterns []Pattern
buildPatterns := func() []Pattern {
if len(patterns) == 0 {
regexes := map[string]string{
"^\\d{1,2}:\\d{1,2}$": "15:4",
"^\\d{1,2}:\\d{1,2}:\\d{1,2}$": "15:4:5",
"^\\d{1,2}:\\d{1,2}:\\d{1,2} [aApP][mM]$": "3:4:5 PM",
"^\\d{1,2}:\\d{1,2} [aApP][mM]$": "3:4 PM",
"^\\d{1,2}/\\d{1,2}/\\d{4}$": "1/2/2006",
"^\\d{1,2}/\\d{1,2}/\\d{2}$": "1/2/06",
"^\\d{1,2}/\\d{1,2}/\\d{2} \\d{1,2}:\\d{1,2}:\\d{1,2}$": "1/2/06 15:4:5",
"^\\d{1,2}/\\d{1,2}/\\d{4} \\d{1,2}:\\d{1,2}:\\d{1,2}$": "1/2/2006 15:4:5",
"^\\d{1,2}/\\d{1,2}/\\d{4} \\d{1,2}:\\d{1,2}$": "1/2/2006 15:4",
"^\\d{1,2}/\\d{1,2}/\\d{4} \\d{1,2}:\\d{1,2} [aApP][mM]$": "1/2/2006 3:4 PM",
"^\\d{1,2}/\\d{1,2}/\\d{4} \\d{1,2}:\\d{1,2}:\\d{1,2} [aApP][mM]$": "1/2/2006 3:4:5 PM",
// year first
"^\\d{4}/\\d{1,2}/\\d{1,2}$": "2006/1/2",
"^\\d{4}/\\d{1,2}/\\d{1,2} \\d{1,2}:\\d{1,2}$": "2006/1/2 15:4",
"^\\d{4}/\\d{1,2}/\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}$": "2006/1/2 15:4:5",
"^\\d{4}/\\d{1,2}/\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2} [aApP][mM]$": "2006/1/2 3:4:5 PM",
"^\\d{4}-\\d{1,2}-\\d{1,2}$": "2006-1-2",
"^\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}$": "2006-1-2 15:4",
"^\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}$": "2006-1-2 15:4:5",
"^\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2} [aApP][mM]$": "2006-1-2 3:4:5 PM",
// yyyy.dd.mm
"^\\d{4}\\.\\d{1,2}\\.\\d{1,2}$": "2006.1.2",
// dd.mm.yyyy
"^\\d{1,2}\\.\\d{1,2}\\.\\d{4}$": "2.1.2006",
"^\\d{1,2}\\.\\d{1,2}\\.\\d{4} \\d{1,2}:\\d{1,2}$": "2.1.2006 15:4",
"^\\d{1,2}\\.\\d{1,2}\\.\\d{4} \\d{1,2}:\\d{1,2}:\\d{1,2}$": "2.1.2006 15:4:5",
// dd.mm.yy
"^\\d{1,2}\\.\\d{1,2}\\.\\d{2}$": "2.1.06",
"^\\d{1,2}\\.\\d{1,2}\\.\\d{2} \\d{1,2}:\\d{1,2}$": "2.1.06 15:4",
"^\\d{1,2}\\.\\d{1,2}\\.\\d{2} \\d{1,2}:\\d{1,2}:\\d{1,2}$": "2.1.06 15:4:5",
}
for regex, p := range regexes {
re := regexp.MustCompile(regex)
pair := Pattern{regex: re, pattern: p}
patterns = append(patterns, pair)
}
return patterns
}
return patterns
}
buildPatterns()
format := ""
for _, regex := range patterns {
if regex.regex.MatchString(input) {
format = regex.pattern
}
}
if format == "" {
panic("No pattern")
}
t, err := time.Parse(format, input)
return t, err
}