ETCD后台服务
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.3 KiB

3 years ago
  1. package models
  2. import (
  3. "database/sql/driver"
  4. "fmt"
  5. "time"
  6. )
  7. /* 自定义时间格式 */
  8. var timeFormart = "2006-01-02 15:04:05" // time.RFC3339
  9. // JSONTime 时间格式别名
  10. type JSONTime time.Time
  11. // UnmarshalJSON 字节转为JSONTime对象
  12. func (t *JSONTime) UnmarshalJSON(data []byte) (err error) {
  13. now, err := time.ParseInLocation(`"`+timeFormart+`"`, string(data), time.UTC)
  14. *t = JSONTime(now)
  15. return
  16. }
  17. // MarshalJSON 将时间对象转为字节
  18. func (t JSONTime) MarshalJSON() ([]byte, error) {
  19. b := make([]byte, 0, len(timeFormart)+2)
  20. b = append(b, '"')
  21. b = time.Time(t).Local().AppendFormat(b, timeFormart)
  22. b = append(b, '"')
  23. return b, nil
  24. }
  25. // String 格式化为文本
  26. func (t JSONTime) String() string {
  27. return time.Time(t).Format(timeFormart)
  28. }
  29. // Format 格式化函数
  30. func (t JSONTime) Format(format string) string {
  31. return time.Time(t).Format(timeFormart)
  32. }
  33. // Value insert timestamp into mysql need this function.
  34. func (t JSONTime) Value() (driver.Value, error) {
  35. var zeroTime time.Time
  36. var ti = time.Time(t)
  37. if ti.UnixNano() == zeroTime.UnixNano() {
  38. return nil, nil
  39. }
  40. return ti, nil
  41. }
  42. // Scan valueof time.Time
  43. func (t *JSONTime) Scan(v interface{}) error {
  44. value, ok := v.(time.Time)
  45. if ok {
  46. *t = JSONTime(value)
  47. return nil
  48. }
  49. return fmt.Errorf("can not convert %v to timestamp", v)
  50. }