GTime.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package models
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. orm2 "github.com/beego/beego/v2/client/orm"
  6. "time"
  7. )
  8. type Time struct {
  9. time.Time
  10. }
  11. // MarshalJSON 序列化为JSON
  12. func (t Time) MarshalJSON() ([]byte, error) {
  13. if t.IsZero() {
  14. return []byte("\"\""), nil
  15. }
  16. stamp := fmt.Sprintf("\"%s\"", t.Format("2006-01-02 15:04:05"))
  17. return []byte(stamp), nil
  18. }
  19. // UnmarshalJSON 反序列化为JSON
  20. func (t *Time) UnmarshalJSON(data []byte) error {
  21. var err error
  22. t.Time, err = time.Parse("2006-01-02 15:04:05", string(data)[1:20])
  23. return err
  24. }
  25. func (t *Time) String() string {
  26. data, _ := json.Marshal(t)
  27. return string(data)
  28. }
  29. func (t *Time) FieldType() int {
  30. return orm2.TypeDateTimeField
  31. }
  32. func (t *Time) SetRaw(value interface{}) error {
  33. switch value.(type) {
  34. case time.Time:
  35. t.Time = value.(time.Time)
  36. }
  37. return nil
  38. }
  39. func (t *Time) RawValue() interface{} {
  40. str := t.Format("2006-01-02 15:04:05")
  41. if str == "0001-01-01 00:00:00" {
  42. return nil
  43. }
  44. return str
  45. }
  46. func (t *Time) NowDbTime() Time {
  47. dbTime := Time{}
  48. dbTime.Time = time.Now()
  49. return dbTime
  50. }
  51. func (t *Time) AddDates(years int, months int, days int) Time {
  52. dbTime := Time{}
  53. dbTime.Time = t.Time.AddDate(years, months, days)
  54. return dbTime
  55. }
  56. func TimeParse(value string) (Time, error) {
  57. dbTime := Time{}
  58. times, err := time.Parse("2006-01-02 15:04:05", value)
  59. dbTime.Time = times
  60. return dbTime, err
  61. }