-
Notifications
You must be signed in to change notification settings - Fork 19
/
dates.go
458 lines (389 loc) · 12.6 KB
/
dates.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
package utils
import (
"bytes"
"math"
"regexp"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
validator "gopkg.in/go-playground/validator.v9"
)
func init() {
Validator.RegisterValidation("date_format", func(fl validator.FieldLevel) bool {
_, err := ToGoDateFormat(fl.Field().String(), DateOnlyFormatting)
return err == nil
})
Validator.RegisterValidation("time_format", func(fl validator.FieldLevel) bool {
_, err := ToGoDateFormat(fl.Field().String(), TimeOnlyFormatting)
return err == nil
})
}
// patterns for date and time formats supported for human-entered data
var patternDayMonthYear = regexp.MustCompile(`\b([0-9]{1,2})[-.\\/_ ]([0-9]{1,2})[-.\\/_ ]([0-9]{4}|[0-9]{2})\b`)
var patternMonthDayYear = regexp.MustCompile(`\b([0-9]{1,2})[-.\\/_ ]([0-9]{1,2})[-.\\/_ ]([0-9]{4}|[0-9]{2})\b`)
var patternYearMonthDay = regexp.MustCompile(`\b([0-9]{4}|[0-9]{2})[-.\\/_ ]([0-9]{1,2})[-.\\/_ ]([0-9]{1,2})\b`)
var patternTime = regexp.MustCompile(`\b(\d{1,2})(?:(?:\:)?(\d{2})(?:\:(\d{2})(?:\.(\d+))?)?)?\W*([aApP][mM])?\b`)
// DateFormat a date format string
type DateFormat string
// TimeFormat a time format string
type TimeFormat string
// standard date and time formats
const (
DateFormatYearMonthDay DateFormat = "YYYY-MM-DD"
DateFormatMonthDayYear DateFormat = "MM-DD-YYYY"
DateFormatDayMonthYear DateFormat = "DD-MM-YYYY"
TimeFormatHourMinute TimeFormat = "tt:mm"
TimeFormatHourMinuteAmPm TimeFormat = "h:mm aa"
TimeFormatHourMinuteSecond TimeFormat = "tt:mm:ss"
TimeFormatHourMinuteSecondAmPm TimeFormat = "h:mm:ss aa"
)
func (df DateFormat) String() string { return string(df) }
func (tf TimeFormat) String() string { return string(tf) }
// format we use for output
var iso8601Default = "2006-01-02T15:04:05.000000Z07:00"
// generic format for parsing any 8601 date
var iso8601Format = "2006-01-02T15:04:05Z07:00"
var iso8601NoSecondsFormat = "2006-01-02T15:04Z07:00"
var iso8601Date = "2006-01-02"
var iso8601Time = "15:04:05.000000"
var isoFormats = []string{iso8601Format, iso8601NoSecondsFormat}
// ZeroDateTime is our uninitialized datetime value
var ZeroDateTime = time.Time{}
func dateFromFormats(currentYear int, pattern *regexp.Regexp, d int, m int, y int, str string) (Date, string, error) {
matches := pattern.FindAllStringSubmatchIndex(str, -1)
for _, match := range matches {
groups := StringSlices(str, match)
// does our day look believable?
day, _ := strconv.Atoi(groups[d])
if day == 0 || day > 31 {
continue
}
month, _ := strconv.Atoi(groups[m])
if month == 0 || month > 12 {
continue
}
year, _ := strconv.Atoi(groups[y])
// convert to four digit year if necessary
if len(groups[y]) == 2 {
if year > currentYear%1000 {
year += 1900
} else {
year += 2000
}
}
remainder := str[match[1]:]
// looks believable, go for it
return NewDate(year, month, day), remainder, nil
}
return ZeroDate, str, errors.Errorf("string '%s' couldn't be parsed as a date", str)
}
// DaysBetween returns the number of calendar days (an int) between the two dates. Note
// that if these are in different timezones then the local calendar day is used for each
// and the difference is calculated from that.
func DaysBetween(date1 time.Time, date2 time.Time) int {
d1 := time.Date(date1.Year(), date1.Month(), date1.Day(), 0, 0, 0, 0, time.UTC)
d2 := time.Date(date2.Year(), date2.Month(), date2.Day(), 0, 0, 0, 0, time.UTC)
return int(d1.Sub(d2) / (time.Hour * 24))
}
// MonthsBetween returns the number of calendar months (an int) between the two dates. Note
// that if these are in different timezones then the local calendar day is used for each
// and the difference is calculated from that.
func MonthsBetween(date1 time.Time, date2 time.Time) int {
// difference in months
months := int(date1.Month() - date2.Month())
// difference in years
months += (date1.Year() - date2.Year()) * 12
return months
}
// DateTimeToISO converts the passed in time.Time to a string in ISO8601 format
func DateTimeToISO(date time.Time) string {
return date.Format(iso8601Default)
}
// DateTimeFromString returns a datetime constructed from the passed in string, or an error if we
// are unable to extract one
func DateTimeFromString(env Environment, str string, fillTime bool) (time.Time, error) {
str = strings.Trim(str, " \n\r\t")
// first see if we can parse in any known ISO formats, if so return that
for _, format := range isoFormats {
parsed, err := time.ParseInLocation(format, str, env.Timezone())
if err == nil {
return parsed, nil
}
}
// otherwise, try to parse according to their env settings
date, remainder, err := parseDate(env, str)
// couldn't find a date? bail
if err != nil {
return ZeroDateTime, err
}
// can we pull out a time from the remainder of the string?
hasTime, timeOfDay := parseTime(remainder)
if !hasTime && fillTime {
timeOfDay = ExtractTimeOfDay(env.Now())
}
// combine our date and time
return time.Date(date.Year, time.Month(date.Month), date.Day, timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Nanos, env.Timezone()), nil
}
// DateFromString returns a date constructed from the passed in string, or an error if we
// are unable to extract one
func DateFromString(env Environment, str string) (Date, error) {
parsed, _, err := parseDate(env, str)
return parsed, err
}
// TimeFromString returns a time of day constructed from the passed in string, or an error if we
// are unable to extract one
func TimeFromString(str string) (TimeOfDay, error) {
hasTime, timeOfDay := parseTime(str)
if !hasTime {
return ZeroTimeOfDay, errors.Errorf("string '%s' couldn't be parsed as a time", str)
}
return timeOfDay, nil
}
func parseDate(env Environment, str string) (Date, string, error) {
str = strings.Trim(str, " \n\r\t")
// try to parse as ISO date
asISO, err := time.ParseInLocation(iso8601Date, str[0:MinInt(len(iso8601Date), len(str))], env.Timezone())
if err == nil {
return ExtractDate(asISO), str[len(iso8601Date):], nil
}
// otherwise, try to parse according to their env settings
currentYear := Now().Year()
switch env.DateFormat() {
case DateFormatYearMonthDay:
return dateFromFormats(currentYear, patternYearMonthDay, 3, 2, 1, str)
case DateFormatDayMonthYear:
return dateFromFormats(currentYear, patternDayMonthYear, 1, 2, 3, str)
case DateFormatMonthDayYear:
return dateFromFormats(currentYear, patternMonthDayYear, 2, 1, 3, str)
}
return ZeroDate, "", errors.Errorf("unknown date format: %s", env.DateFormat())
}
func replaceTime(d time.Time, t time.Time) time.Time {
return time.Date(d.Year(), d.Month(), d.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), t.Location())
}
func parseTime(str string) (bool, TimeOfDay) {
matches := patternTime.FindAllStringSubmatch(str, -1)
for _, match := range matches {
hour, _ := strconv.Atoi(match[1])
minute, _ := strconv.Atoi(match[2])
second, _ := strconv.Atoi(match[3])
ampm := strings.ToLower(match[5])
// do we have an AM/PM
if ampm == "pm" {
hour += 12
}
nanosStr := match[4]
nanos := 0
if nanosStr != "" {
// can only read nano second accuracy
if len(nanosStr) > 9 {
nanosStr = nanosStr[0:9]
}
nanos, _ = strconv.Atoi(nanosStr)
nanos *= int(math.Pow(10, float64(9-len(nanosStr))))
}
// 24:00:00.000000 is a special case for midnight
if hour == 24 && minute == 0 && second == 0 && nanos == 0 {
hour = 0
}
// is our time valid?
if hour > 24 {
continue
}
if minute > 60 {
continue
}
if second > 60 {
continue
}
return true, NewTimeOfDay(hour, minute, second, nanos)
}
return false, ZeroTimeOfDay
}
// FormattingMode describe a mode of formatting dates, times, datetimes
type FormattingMode int
// supported formatting modes
const (
DateOnlyFormatting FormattingMode = iota
TimeOnlyFormatting
DateTimeFormatting
)
var ignoredFormattingRunes = map[rune]bool{' ': true, ':': true, '/': true, '.': true, 'T': true, '-': true, '_': true}
// ToGoDateFormat converts the passed in format to a GoLang format string.
//
// If mode is DateOnlyFormatting or DateTimeFormatting, the following sequences are accepted:
//
// `YY` - last two digits of year 0-99
// `YYYY` - four digits of your 0000-9999
// `M` - month 1-12
// `MM` - month 01-12
// `D` - day of month, 1-31
// `DD` - day of month, zero padded 0-31
//
// If mode is TimeOnlyFormatting or DateTimeFormatting, the following sequences are accepted:
//
// `h` - hour of the day 1-12
// `hh` - hour of the day 01-12
// `tt` - twenty four hour of the day 01-23
// `m` - minute 0-59
// `mm` - minute 00-59
// `s` - second 0-59
// `ss` - second 00-59
// `fff` - milliseconds
// `ffffff` - microseconds
// `fffffffff` - nanoseconds
// `aa` - am or pm
// `AA` - AM or PM
// `Z` - hour and minute offset from UTC, or Z for UTC
// `ZZZ` - hour and minute offset from UTC
//
// ignored chars: ' ', ':', ',', 'T', '-', '_', '/'
func ToGoDateFormat(format string, mode FormattingMode) (string, error) {
runes := []rune(format)
goFormat := bytes.Buffer{}
repeatCount := func(runes []rune, offset int, test rune) int {
count := 0
for i := offset; i < len(runes); i++ {
if runes[i] == test {
count++
} else {
break
}
}
return count
}
for i := 0; i < len(runes); i++ {
r := runes[i]
count := repeatCount(runes, i, r)
if mode == DateOnlyFormatting || mode == DateTimeFormatting {
switch r {
case 'Y':
if count == 2 {
goFormat.WriteString("06")
i++
} else if count == 4 {
goFormat.WriteString("2006")
i += 3
} else {
return "", errors.Errorf("invalid date format, invalid count of 'Y' format: %d", count)
}
continue
case 'M':
if count == 1 {
goFormat.WriteString("1")
} else if count == 2 {
goFormat.WriteString("01")
i++
} else {
return "", errors.Errorf("invalid date format, invalid count of 'M' format: %d", count)
}
continue
case 'D':
if count == 1 {
goFormat.WriteString("2")
} else if count >= 2 {
goFormat.WriteString("02")
i++
}
continue
}
}
if mode == TimeOnlyFormatting || mode == DateTimeFormatting {
switch r {
case 'f':
if count == 9 {
goFormat.WriteString("000000000")
i += 8
} else if count == 6 {
goFormat.WriteString("000000")
i += 5
} else if count == 3 {
goFormat.WriteString("000")
i += 2
} else {
return "", errors.Errorf("invalid date format, invalid count of 'f' format: %d", count)
}
continue
case 'h':
if count == 1 {
goFormat.WriteString("3")
} else if count == 2 {
goFormat.WriteString("03")
i++
}
continue
case 't':
if count == 2 {
goFormat.WriteString("15")
i++
} else {
return "", errors.Errorf("invalid date format, invalid count of 't' format: %d", count)
}
continue
case 'm':
if count == 1 {
goFormat.WriteString("4")
} else if count == 2 {
goFormat.WriteString("04")
i++
} else {
return "", errors.Errorf("invalid date format, invalid count of 'm' format: %d", count)
}
continue
case 's':
if count == 1 {
goFormat.WriteString("5")
} else if count == 2 {
goFormat.WriteString("05")
i++
} else {
return "", errors.Errorf("invalid date format, invalid count of 's' format: %d", count)
}
continue
case 'a':
if count == 2 {
goFormat.WriteString("pm")
i++
} else {
return "", errors.Errorf("invalid date format, invalid count of 'a' format: %d", count)
}
continue
case 'A':
if count == 2 {
goFormat.WriteString("PM")
i++
} else {
return "", errors.Errorf("invalid date format, invalid count of 'A' format: %d", count)
}
continue
}
}
if mode == DateTimeFormatting {
switch r {
case 'Z':
if count == 1 {
goFormat.WriteString("Z07:00")
} else if count == 3 {
goFormat.WriteString("-07:00")
i += 2
} else {
return "", errors.Errorf("invalid date format, invalid count of 'Z' format: %d", count)
}
continue
}
}
if ignoredFormattingRunes[r] {
goFormat.WriteRune(r)
} else {
return "", errors.Errorf("invalid date format, unknown format char: %c", r)
}
}
return goFormat.String(), nil
}
// DateToUTCRange returns the UTC time range of the given day
func DateToUTCRange(d time.Time, tz *time.Location) (time.Time, time.Time) {
localMidnight := time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, d.Location())
utcMidnight := localMidnight.In(tz)
return utcMidnight, utcMidnight.Add(24 * time.Hour)
}