time.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package replication
  2. import (
  3. "fmt"
  4. "strings"
  5. "time"
  6. )
  7. var (
  8. fracTimeFormat []string
  9. )
  10. // fracTime is a help structure wrapping Golang Time.
  11. type fracTime struct {
  12. time.Time
  13. // Dec must in [0, 6]
  14. Dec int
  15. timestampStringLocation *time.Location
  16. }
  17. func (t fracTime) String() string {
  18. tt := t.Time
  19. if t.timestampStringLocation != nil {
  20. tt = tt.In(t.timestampStringLocation)
  21. }
  22. return tt.Format(fracTimeFormat[t.Dec])
  23. }
  24. func formatZeroTime(frac int, dec int) string {
  25. if dec == 0 {
  26. return "0000-00-00 00:00:00"
  27. }
  28. s := fmt.Sprintf("0000-00-00 00:00:00.%06d", frac)
  29. // dec must < 6, if frac is 924000, but dec is 3, we must output 924 here.
  30. return s[0 : len(s)-(6-dec)]
  31. }
  32. func formatBeforeUnixZeroTime(year, month, day, hour, minute, second, frac, dec int) string {
  33. if dec == 0 {
  34. return fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d", year, month, day, hour, minute, second)
  35. }
  36. s := fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d.%06d", year, month, day, hour, minute, second, frac)
  37. // dec must < 6, if frac is 924000, but dec is 3, we must output 924 here.
  38. return s[0 : len(s)-(6-dec)]
  39. }
  40. func microSecTimestampToTime(ts uint64) time.Time {
  41. if ts == 0 {
  42. return time.Time{}
  43. }
  44. return time.Unix(int64(ts/1000000), int64(ts%1000000)*1000)
  45. }
  46. func init() {
  47. fracTimeFormat = make([]string, 7)
  48. fracTimeFormat[0] = "2006-01-02 15:04:05"
  49. for i := 1; i <= 6; i++ {
  50. fracTimeFormat[i] = fmt.Sprintf("2006-01-02 15:04:05.%s", strings.Repeat("0", i))
  51. }
  52. }