|
| 1 | +package database |
| 2 | + |
| 3 | +import ( |
| 4 | + "database/sql/driver" |
| 5 | + "fmt" |
| 6 | + "time" |
| 7 | +) |
| 8 | + |
| 9 | +type PgTimeTz struct { |
| 10 | + time.Time |
| 11 | +} |
| 12 | + |
| 13 | +// Value Implements Valuer interface for writing to DB |
| 14 | +func (pt PgTimeTz) Value() (driver.Value, error) { |
| 15 | + // 格式化为 HH:MM:SS.ssssss |
| 16 | + return pt.String(), nil |
| 17 | +} |
| 18 | + |
| 19 | +// Scan Implements Scanner interface for reading from DB |
| 20 | +func (pt *PgTimeTz) Scan(value interface{}) error { |
| 21 | + switch v := value.(type) { |
| 22 | + case time.Time: |
| 23 | + pt.Time = v |
| 24 | + case []byte: |
| 25 | + // Parse byte array in HH:MM:SS[.ssssss]+TZ format |
| 26 | + t, err := time.Parse("15:04:05.999999-07", string(v)) |
| 27 | + if err != nil { |
| 28 | + return fmt.Errorf("timetz parsing failed: %v", err) |
| 29 | + } |
| 30 | + pt.Time = t |
| 31 | + case string: |
| 32 | + t, err := time.Parse("15:04:05.999999-07", v) |
| 33 | + if err != nil { |
| 34 | + return fmt.Errorf("timetz parsing failed: %v", err) |
| 35 | + } |
| 36 | + pt.Time = t |
| 37 | + default: |
| 38 | + return fmt.Errorf("unsupported type: %T", value) |
| 39 | + } |
| 40 | + return nil |
| 41 | +} |
| 42 | + |
| 43 | +func (pt PgTimeTz) MarshalJSON() ([]byte, error) { |
| 44 | + return []byte(fmt.Sprintf(`"%s"`, pt.Format("15:04:05.999999-07"))), nil |
| 45 | +} |
| 46 | + |
| 47 | +func (pt *PgTimeTz) UnmarshalJSON(data []byte) error { |
| 48 | + t, err := time.Parse(`"15:04:05.999999-07"`, string(data)) |
| 49 | + if err != nil { |
| 50 | + return err |
| 51 | + } |
| 52 | + pt.Time = t |
| 53 | + return nil |
| 54 | +} |
| 55 | + |
| 56 | +func (pt PgTimeTz) String() string { |
| 57 | + return pt.Format("15:04:05.999999-07") |
| 58 | +} |
| 59 | + |
| 60 | +func (pt PgTimeTz) His(loc *time.Location) string { |
| 61 | + return pt.Time.In(loc).Format("15:04:05") |
| 62 | +} |
| 63 | + |
| 64 | +func (pt PgTimeTz) Add(d time.Duration) PgTime { |
| 65 | + return PgTime{ |
| 66 | + Time: pt.Time.Add(d), |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +func StrToPgTimeTz(str string) PgTimeTz { |
| 71 | + tm, _ := time.Parse("15:04:05.999999-07", str) |
| 72 | + return PgTimeTz{tm} |
| 73 | +} |
0 commit comments