git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/timex/time.go (about) 1 package timex 2 3 import ( 4 "database/sql/driver" 5 "fmt" 6 "time" 7 ) 8 9 type Time int64 10 11 func Now() Time { 12 return Time(time.Now().UTC().UnixMilli()) 13 } 14 15 func (t Time) Unix() int64 { 16 return int64(t) / 1000 17 } 18 19 func (t Time) StdTime() time.Time { 20 return time.Unix(0, int64(t)*1_000_000).UTC() 21 } 22 23 func (t *Time) Scan(val any) (err error) { 24 switch v := val.(type) { 25 case int64: 26 *t = Time(v) 27 return nil 28 case string: 29 tt, err := time.Parse(time.RFC3339, v) 30 if err != nil { 31 return err 32 } 33 *t = Time(tt.UTC().UnixMilli()) 34 return nil 35 default: 36 return fmt.Errorf("Time.Scan: Unsupported type: %T", v) 37 } 38 } 39 40 func (t Time) Value() (driver.Value, error) { 41 return t, nil 42 } 43 44 func (t Time) MarshalText() (ret []byte, err error) { 45 return t.StdTime().MarshalText() 46 } 47 48 func (t Time) MarshalJSON() ([]byte, error) { 49 return t.StdTime().MarshalJSON() 50 } 51 52 func (t *Time) UnmarshalText(data []byte) (err error) { 53 var tt time.Time 54 55 err = tt.UnmarshalText(data) 56 if err != nil { 57 return err 58 } 59 60 *t = Time(tt.UnixMilli()) 61 return nil 62 } 63 64 func (t *Time) UnmarshalJSON(data []byte) (err error) { 65 var tt time.Time 66 67 err = tt.UnmarshalJSON(data) 68 if err != nil { 69 return err 70 } 71 72 *t = Time(tt.UnixMilli()) 73 return nil 74 } 75 76 func (t Time) String() string { 77 ret, _ := t.MarshalText() 78 return string(ret) 79 }