bjtime.go 936 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package protocol
  2. import (
  3. "time"
  4. )
  5. var beijingtz *time.Location
  6. func init() {
  7. loc, err := time.LoadLocation("Asia/Shanghai")
  8. if err != nil {
  9. beijingtz = time.FixedZone("CST", 8*3600)
  10. } else {
  11. beijingtz = loc
  12. }
  13. }
  14. func BJNow() time.Time {
  15. return time.Now().In(beijingtz)
  16. }
  17. func ToBJTime(t time.Time) time.Time {
  18. return t.In(beijingtz)
  19. }
  20. type BJTime time.Time
  21. const (
  22. timeFormart = "2006-01-02 15:04:05"
  23. )
  24. func (t *BJTime) UnmarshalJSON(data []byte) (err error) {
  25. now, err := time.ParseInLocation(`"`+timeFormart+`"`, string(data), beijingtz)
  26. *t = BJTime(now)
  27. return
  28. }
  29. func (t BJTime) MarshalJSON() ([]byte, error) {
  30. b := make([]byte, 0, len(timeFormart)+2)
  31. b = append(b, '"')
  32. tt := time.Time(t)
  33. if !tt.IsZero() {
  34. b = tt.AppendFormat(b, timeFormart)
  35. }
  36. b = append(b, '"')
  37. return b, nil
  38. }
  39. func (t BJTime) String() string {
  40. tt := time.Time(t)
  41. if tt.IsZero() {
  42. return ""
  43. }
  44. return tt.Format(timeFormart)
  45. }