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