-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstrptime.go
202 lines (180 loc) · 5.97 KB
/
strptime.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
/*
Copyright (c) 2013 Jeremy Jay
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// Package strptime provides a C-style strptime wrappers for time.Parse.
//
// It supports the following subset of format strings (stolen from python docs):
// %d Day of the month as a zero-padded decimal number.
// %b Month as locale’s abbreviated name.
// %B Month as locale’s full name.
// %m Month as a zero-padded decimal number.
// %y Year without century as a zero-padded decimal number.
// %Y Year with century as a decimal number.
// %H Hour (24-hour clock) as a zero-padded decimal number.
// %I Hour (12-hour clock) as a zero-padded decimal number.
// %p Locale’s equivalent of either AM or PM.
// %M Minute as a zero-padded decimal number.
// %S Second as a zero-padded decimal number.
// %f Microsecond as a decimal number, zero-padded on the left.
// %z UTC offset in the form +HHMM or -HHMM.
// %Z Time zone name. UTC, EST, CST
// %% A literal '%' character.
//
// BUG(pbnjay): If an unsupported specifier is used, it may NOT directly precede a
// supported specifier (i.e. there must be intervening text to match first)
package strptime
import (
"errors"
"strings"
"time"
)
// Parse accepts a percent-encoded strptime format string, converts it for use with
// time.Parse, and returns the resulting time.Time value. If non-date-related format
// text does not match within the string value, then ErrFormatMismatch will be returned.
// Errors from time.Parse are passed through untouched.
//
// If a unsupported format specifier is provided, it will be ignored and matching
// text will be skipped. To receive errors for unsupported formats, use ParseStrict or call Check.
func Parse(value, format string) (time.Time, error) {
return strptime(value, format, true)
}
// ParseStrict returns ErrFormatUnsupported for unsupported formats strings, but is otherwise
// identical to Parse.
func ParseStrict(value, format string) (time.Time, error) {
return strptime(value, format, false)
}
// MustParse is a wrapper for Parse which panics on any error.
func MustParse(value, format string) time.Time {
t, err := strptime(value, format, true)
if err != nil {
panic(err)
}
return t
}
// Check verifies that format is a fully-supported strptime format string for this implementation.
func Check(format string) error {
parts := strings.Split(format, "%")
for _, ps := range parts {
// since we split on '%', this is the format code
c := int(ps[0])
if c == '%' {
continue
}
if _, found := formatMap[c]; !found {
return ErrFormatUnsupported
}
}
return nil
}
func strptime(value, format string, ignoreUnsupported bool) (time.Time, error) {
parseStr := ""
parseFmt := ""
vi := 0
parts := strings.Split(format, "%")
for pi, ps := range parts {
if pi == 0 {
// check prefix string
if value[:len(ps)] != ps {
return time.Time{}, ErrFormatMismatch
}
vi += len(ps)
continue
}
// since we split on '%', this is the format code
c := int(ps[0])
if c == '%' { // handle %% quickly
if ps != value[vi:vi+len(ps)] {
return time.Time{}, ErrFormatMismatch
}
vi += len(ps)
continue
}
// Check if format is supported and get the time.Parse translation
f, supported := formatMap[c]
if !supported && !ignoreUnsupported {
return time.Time{}, ErrFormatUnsupported
}
// Check the intervening text between format strings.
// There may be some edge cases where this isn't quite right
// but if that's the case you've got other problems...
vj := len(ps) - 1
if vj > 0 {
vj = strings.Index(value[vi:], ps[1:])
}
if vj == -1 {
return time.Time{}, ErrFormatMismatch
}
if supported {
// Build up a new format and date string
if vj == 0 { // no intervening text
if c == 'f' {
vj = len(value) - vi
} else {
vj = len(f)
if vj > len(value)-vi {
return time.Time{}, ErrFormatMismatch
}
}
}
if c == 'f' {
parseFmt += "." + f
parseStr += "." + value[vi:vi+vj]
} else if c == 'p' {
parseFmt += " " + f
parseStr += " " + strings.ToUpper(value[vi:vi+vj])
} else {
parseFmt += " " + f
parseStr += " " + value[vi:vi+vj]
}
}
if !supported && vj == 0 {
// ignore to the end of the string
vi = len(value)
} else {
vi += (len(ps) - 1) + vj
}
}
if vi < len(value) {
// extra text on end of value
return time.Time{}, ErrFormatMismatch
}
return time.Parse(parseFmt, parseStr)
}
var (
// ErrFormatMismatch means that intervening text in the strptime format string did not
// match within the parsed string.
ErrFormatMismatch = errors.New("date format mismatch")
// ErrFormatUnsupported means that the format string includes unsupport percent-escapes.
ErrFormatUnsupported = errors.New("date format contains unsupported percent-encodings")
formatMap = map[int]string{
'd': "02",
'b': "Jan",
'B': "January",
'm': "01",
'y': "06",
'Y': "2006",
'H': "15",
'I': "03",
'p': "PM",
'M': "04",
'S': "05",
'f': "999999",
'z': "-0700",
'Z': "MST",
}
)