mytime.go 1.9 KB

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