dayduration.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package main
  2. // Add a function similar to time.Duration.String() to
  3. // pretty print an "uptime duration".
  4. import (
  5. "time"
  6. )
  7. type DayDuration struct {
  8. time.Duration
  9. }
  10. func fmtInt(buf []byte, v uint64) int {
  11. w := len(buf)
  12. if v == 0 {
  13. w--
  14. buf[w] = '0'
  15. } else {
  16. for v > 0 {
  17. w--
  18. buf[w] = byte(v%10) + '0'
  19. v /= 10
  20. }
  21. }
  22. return w
  23. }
  24. // DayString returns string version of the time duration without too much precision.
  25. // Copied from time/time.go
  26. func (d DayDuration) DayString() string {
  27. var buf [32]byte
  28. w := len(buf)
  29. u := uint64(d.Nanoseconds())
  30. neg := d.Nanoseconds() < 0
  31. if neg {
  32. u = -u
  33. }
  34. if u < uint64(time.Second) {
  35. // Don't show times less than a second
  36. w -= 2
  37. buf[w] = '0'
  38. buf[w+1] = 's'
  39. } else {
  40. w--
  41. buf[w] = 's'
  42. // Skip fractional seconds
  43. u /= uint64(time.Second)
  44. // u is now integer seconds
  45. w = fmtInt(buf[:w], u%60)
  46. u /= 60
  47. // u is now integer minutes
  48. if u > 0 {
  49. w--
  50. buf[w] = ' '
  51. w--
  52. buf[w] = 'm'
  53. w = fmtInt(buf[:w], u%60)
  54. u /= 60
  55. // u is now integer hours
  56. if u > 0 {
  57. w--
  58. buf[w] = ' '
  59. w--
  60. buf[w] = 'h'
  61. w = fmtInt(buf[:w], u%24)
  62. u /= 24
  63. }
  64. // u is now integer days
  65. if u > 0 {
  66. w--
  67. buf[w] = ' '
  68. w--
  69. buf[w] = 'd'
  70. w = fmtInt(buf[:w], u)
  71. }
  72. }
  73. }
  74. if neg {
  75. w--
  76. buf[w] = '-'
  77. }
  78. return string(buf[w:])
  79. }