time.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package utils
  2. import (
  3. "database/sql/driver"
  4. "fmt"
  5. "time"
  6. )
  7. type DateTime time.Time
  8. const (
  9. DateLayout = "2006-01-02"
  10. DateTimeLayout = "2006-01-02 15:04:05"
  11. BuildTimeLayout = "2006.0102.150405"
  12. TimestampLayout = "20060102150405"
  13. )
  14. var StartTime = time.Now()
  15. func (dt *DateTime) UnmarshalJSON(data []byte) (err error) {
  16. now, err := time.ParseInLocation(DateTimeLayout, string(data), time.Local)
  17. *dt = DateTime(now)
  18. return
  19. }
  20. func (dt DateTime) MarshalJSON() ([]byte, error) {
  21. b := make([]byte, 0, len(DateTimeLayout)+2)
  22. b = append(b, '"')
  23. b = time.Time(dt).AppendFormat(b, DateTimeLayout)
  24. b = append(b, '"')
  25. return b, nil
  26. }
  27. func (dt DateTime) Value() (driver.Value, error) {
  28. var zeroTime time.Time
  29. ti := time.Time(dt)
  30. if ti.UnixNano() == zeroTime.UnixNano() {
  31. return nil, nil
  32. }
  33. return ti, nil
  34. }
  35. func (dt *DateTime) Scan(v interface{}) error {
  36. if value, ok := v.(time.Time); ok {
  37. *dt = DateTime(value)
  38. return nil
  39. }
  40. return nil
  41. }
  42. func (dt DateTime) String() string {
  43. return time.Time(dt).Format(DateTimeLayout)
  44. }
  45. func UpTime() time.Duration {
  46. return time.Since(StartTime)
  47. }
  48. func UpTimeString() string {
  49. d := UpTime()
  50. days := d / (time.Hour * 24)
  51. d -= days * 24 * time.Hour
  52. hours := d / time.Hour
  53. d -= hours * time.Hour
  54. minutes := d / time.Minute
  55. d -= minutes * time.Minute
  56. seconds := d / time.Second
  57. return fmt.Sprintf("%d Days %d Hours %d Mins %d Secs", days, hours, minutes, seconds)
  58. }