mytime.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package utils
  2. import (
  3. "time"
  4. )
  5. var bjlocation *time.Location
  6. func init() {
  7. loc, err := time.LoadLocation("Asia/Shanghai")
  8. if err != nil {
  9. bjlocation = time.FixedZone("CST", 8*3600)
  10. } else {
  11. bjlocation = loc
  12. }
  13. }
  14. func Unix2Time(sec int64) string {
  15. return time.Unix(sec, 0).Format("2006-01-02 15:04:05")
  16. }
  17. func MlNow() time.Time {
  18. return time.Now().In(bjlocation)
  19. }
  20. func MlParseTimeX(layout, strTime string) (time.Time, error) {
  21. return time.ParseInLocation(layout, strTime, bjlocation)
  22. }
  23. type MLTime time.Time
  24. const (
  25. timeFormart = "2006-01-02 15:04:05"
  26. )
  27. func (t *MLTime) UnmarshalJSON(data []byte) (err error) {
  28. now, err := time.ParseInLocation(`"`+timeFormart+`"`, string(data), bjlocation)
  29. *t = MLTime(now)
  30. return
  31. }
  32. func (t MLTime) MarshalJSON() ([]byte, error) {
  33. b := make([]byte, 0, len(timeFormart)+2)
  34. b = append(b, '"')
  35. tt := time.Time(t)
  36. if !tt.IsZero() {
  37. b = tt.AppendFormat(b, timeFormart)
  38. }
  39. b = append(b, '"')
  40. return b, nil
  41. }
  42. func (t MLTime) String() string {
  43. tt := time.Time(t)
  44. if tt.IsZero() {
  45. return ""
  46. }
  47. return tt.Format(timeFormart)
  48. }
  49. type MLTimeEx time.Time
  50. const (
  51. timeFormartEx = "2006-01-02 15:04:05.000"
  52. )
  53. func (t *MLTimeEx) UnmarshalJSON(data []byte) (err error) {
  54. now, err := time.ParseInLocation(`"`+timeFormartEx+`"`, string(data), bjlocation)
  55. *t = MLTimeEx(now)
  56. return
  57. }
  58. func (t MLTimeEx) MarshalJSON() ([]byte, error) {
  59. b := make([]byte, 0, len(timeFormartEx)+2)
  60. b = append(b, '"')
  61. tt := time.Time(t)
  62. if !tt.IsZero() {
  63. b = tt.AppendFormat(b, timeFormartEx)
  64. }
  65. b = append(b, '"')
  66. return b, nil
  67. }
  68. func (t MLTimeEx) String() string {
  69. tt := time.Time(t)
  70. if tt.IsZero() {
  71. return ""
  72. }
  73. return tt.Format(timeFormartEx)
  74. }