github.com/octohelm/storage@v0.0.0-20240516030302-1ac2cc1ea347/pkg/datatypes/datetime.go (about) 1 package datatypes 2 3 import ( 4 "database/sql" 5 "database/sql/driver" 6 "encoding" 7 "fmt" 8 "time" 9 ) 10 11 var ( 12 DatetimeZero = Datetime(time.Time{}) 13 ) 14 15 // openapi:strfmt date-time 16 type Datetime time.Time 17 18 func (Datetime) DataType(e string) string { 19 return "timestamp" 20 } 21 22 func ParseDatetimeFromString(s string) (dt Datetime, err error) { 23 var t time.Time 24 t, err = time.Parse(time.RFC3339, s) 25 dt = Datetime(t) 26 return 27 } 28 29 func ParseDatetimeFromStringWithFormatterInCST(s, formatter string) (dt Datetime, err error) { 30 var t time.Time 31 t, err = time.ParseInLocation(formatter, s, CST) 32 dt = Datetime(t) 33 return 34 } 35 36 var _ interface { 37 sql.Scanner 38 driver.Valuer 39 } = (*Datetime)(nil) 40 41 func (dt *Datetime) Scan(value interface{}) error { 42 switch v := value.(type) { 43 case time.Time: 44 *dt = Datetime(time.Unix(v.Unix(), 0)) 45 case nil: 46 *dt = DatetimeZero 47 default: 48 return fmt.Errorf("cannot sql.Scan() strfmt.Datetime from: %#v", v) 49 } 50 return nil 51 } 52 53 func (dt Datetime) Value() (driver.Value, error) { 54 return time.Unix(dt.Unix(), 0), nil 55 } 56 57 func (dt Datetime) String() string { 58 if dt.IsZero() { 59 return "" 60 } 61 return time.Time(dt).In(CST).Format(time.RFC3339) 62 } 63 64 func (dt Datetime) Format(layout string) string { 65 return time.Time(dt).In(CST).Format(layout) 66 } 67 68 var _ interface { 69 encoding.TextMarshaler 70 encoding.TextUnmarshaler 71 } = (*Datetime)(nil) 72 73 func (dt Datetime) MarshalText() ([]byte, error) { 74 return []byte(dt.String()), nil 75 } 76 77 func (dt *Datetime) UnmarshalText(data []byte) (err error) { 78 str := string(data) 79 if len(str) == 0 || str == "0" { 80 return nil 81 } 82 *dt, err = ParseDatetimeFromString(str) 83 return 84 } 85 86 func (dt Datetime) Unix() int64 { 87 return time.Time(dt).Unix() 88 } 89 90 func (dt Datetime) IsZero() bool { 91 unix := dt.Unix() 92 return unix == 0 || unix == DatetimeZero.Unix() 93 } 94 95 func (dt Datetime) In(loc *time.Location) Datetime { 96 return Datetime(time.Time(dt).In(loc)) 97 }