Path: blob/main/vendor/github.com/spf13/cast/internal/time.go
2880 views
package internal12import (3"fmt"4"time"5)67//go:generate stringer -type=TimeFormatType89type TimeFormatType int1011const (12TimeFormatNoTimezone TimeFormatType = iota13TimeFormatNamedTimezone14TimeFormatNumericTimezone15TimeFormatNumericAndNamedTimezone16TimeFormatTimeOnly17)1819type TimeFormat struct {20Format string21Typ TimeFormatType22}2324func (f TimeFormat) HasTimezone() bool {25// We don't include the formats with only named timezones, see26// https://github.com/golang/go/issues/19694#issuecomment-28910352227return f.Typ >= TimeFormatNumericTimezone && f.Typ <= TimeFormatNumericAndNamedTimezone28}2930var TimeFormats = []TimeFormat{31// Keep common formats at the top.32{"2006-01-02", TimeFormatNoTimezone},33{time.RFC3339, TimeFormatNumericTimezone},34{"2006-01-02T15:04:05", TimeFormatNoTimezone}, // iso8601 without timezone35{time.RFC1123Z, TimeFormatNumericTimezone},36{time.RFC1123, TimeFormatNamedTimezone},37{time.RFC822Z, TimeFormatNumericTimezone},38{time.RFC822, TimeFormatNamedTimezone},39{time.RFC850, TimeFormatNamedTimezone},40{"2006-01-02 15:04:05.999999999 -0700 MST", TimeFormatNumericAndNamedTimezone}, // Time.String()41{"2006-01-02T15:04:05-0700", TimeFormatNumericTimezone}, // RFC3339 without timezone hh:mm colon42{"2006-01-02 15:04:05Z0700", TimeFormatNumericTimezone}, // RFC3339 without T or timezone hh:mm colon43{"2006-01-02 15:04:05", TimeFormatNoTimezone},44{time.ANSIC, TimeFormatNoTimezone},45{time.UnixDate, TimeFormatNamedTimezone},46{time.RubyDate, TimeFormatNumericTimezone},47{"2006-01-02 15:04:05Z07:00", TimeFormatNumericTimezone},48{"02 Jan 2006", TimeFormatNoTimezone},49{"2006-01-02 15:04:05 -07:00", TimeFormatNumericTimezone},50{"2006-01-02 15:04:05 -0700", TimeFormatNumericTimezone},51{time.Kitchen, TimeFormatTimeOnly},52{time.Stamp, TimeFormatTimeOnly},53{time.StampMilli, TimeFormatTimeOnly},54{time.StampMicro, TimeFormatTimeOnly},55{time.StampNano, TimeFormatTimeOnly},56}5758func ParseDateWith(s string, location *time.Location, formats []TimeFormat) (d time.Time, e error) {59for _, format := range formats {60if d, e = time.Parse(format.Format, s); e == nil {6162// Some time formats have a zone name, but no offset, so it gets63// put in that zone name (not the default one passed in to us), but64// without that zone's offset. So set the location manually.65if format.Typ <= TimeFormatNamedTimezone {66if location == nil {67location = time.Local68}69year, month, day := d.Date()70hour, min, sec := d.Clock()71d = time.Date(year, month, day, hour, min, sec, d.Nanosecond(), location)72}7374return75}76}77return d, fmt.Errorf("unable to parse date: %s", s)78}798081