Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
kardolus
GitHub Repository: kardolus/chatgpt-cli
Path: blob/main/vendor/github.com/spf13/cast/internal/time.go
2880 views
1
package internal
2
3
import (
4
"fmt"
5
"time"
6
)
7
8
//go:generate stringer -type=TimeFormatType
9
10
type TimeFormatType int
11
12
const (
13
TimeFormatNoTimezone TimeFormatType = iota
14
TimeFormatNamedTimezone
15
TimeFormatNumericTimezone
16
TimeFormatNumericAndNamedTimezone
17
TimeFormatTimeOnly
18
)
19
20
type TimeFormat struct {
21
Format string
22
Typ TimeFormatType
23
}
24
25
func (f TimeFormat) HasTimezone() bool {
26
// We don't include the formats with only named timezones, see
27
// https://github.com/golang/go/issues/19694#issuecomment-289103522
28
return f.Typ >= TimeFormatNumericTimezone && f.Typ <= TimeFormatNumericAndNamedTimezone
29
}
30
31
var TimeFormats = []TimeFormat{
32
// Keep common formats at the top.
33
{"2006-01-02", TimeFormatNoTimezone},
34
{time.RFC3339, TimeFormatNumericTimezone},
35
{"2006-01-02T15:04:05", TimeFormatNoTimezone}, // iso8601 without timezone
36
{time.RFC1123Z, TimeFormatNumericTimezone},
37
{time.RFC1123, TimeFormatNamedTimezone},
38
{time.RFC822Z, TimeFormatNumericTimezone},
39
{time.RFC822, TimeFormatNamedTimezone},
40
{time.RFC850, TimeFormatNamedTimezone},
41
{"2006-01-02 15:04:05.999999999 -0700 MST", TimeFormatNumericAndNamedTimezone}, // Time.String()
42
{"2006-01-02T15:04:05-0700", TimeFormatNumericTimezone}, // RFC3339 without timezone hh:mm colon
43
{"2006-01-02 15:04:05Z0700", TimeFormatNumericTimezone}, // RFC3339 without T or timezone hh:mm colon
44
{"2006-01-02 15:04:05", TimeFormatNoTimezone},
45
{time.ANSIC, TimeFormatNoTimezone},
46
{time.UnixDate, TimeFormatNamedTimezone},
47
{time.RubyDate, TimeFormatNumericTimezone},
48
{"2006-01-02 15:04:05Z07:00", TimeFormatNumericTimezone},
49
{"02 Jan 2006", TimeFormatNoTimezone},
50
{"2006-01-02 15:04:05 -07:00", TimeFormatNumericTimezone},
51
{"2006-01-02 15:04:05 -0700", TimeFormatNumericTimezone},
52
{time.Kitchen, TimeFormatTimeOnly},
53
{time.Stamp, TimeFormatTimeOnly},
54
{time.StampMilli, TimeFormatTimeOnly},
55
{time.StampMicro, TimeFormatTimeOnly},
56
{time.StampNano, TimeFormatTimeOnly},
57
}
58
59
func ParseDateWith(s string, location *time.Location, formats []TimeFormat) (d time.Time, e error) {
60
for _, format := range formats {
61
if d, e = time.Parse(format.Format, s); e == nil {
62
63
// Some time formats have a zone name, but no offset, so it gets
64
// put in that zone name (not the default one passed in to us), but
65
// without that zone's offset. So set the location manually.
66
if format.Typ <= TimeFormatNamedTimezone {
67
if location == nil {
68
location = time.Local
69
}
70
year, month, day := d.Date()
71
hour, min, sec := d.Clock()
72
d = time.Date(year, month, day, hour, min, sec, d.Nanosecond(), location)
73
}
74
75
return
76
}
77
}
78
return d, fmt.Errorf("unable to parse date: %s", s)
79
}
80
81