duration.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. // Package units provides helper function to parse and print size and time units
  2. // in human-readable format.
  3. package units
  4. import (
  5. "fmt"
  6. "time"
  7. )
  8. // HumanDuration returns a human-readable approximation of a duration
  9. // (eg. "About a minute", "4 hours ago", etc.).
  10. func HumanDuration(d time.Duration) string {
  11. if seconds := int(d.Seconds()); seconds < 1 {
  12. return "Less than a second"
  13. } else if seconds < 60 {
  14. return fmt.Sprintf("%d seconds", seconds)
  15. } else if minutes := int(d.Minutes()); minutes == 1 {
  16. return "About a minute"
  17. } else if minutes < 60 {
  18. return fmt.Sprintf("%d minutes", minutes)
  19. } else if hours := int(d.Hours()); hours == 1 {
  20. return "About an hour"
  21. } else if hours < 48 {
  22. return fmt.Sprintf("%d hours", hours)
  23. } else if hours < 24*7*2 {
  24. return fmt.Sprintf("%d days", hours/24)
  25. } else if hours < 24*30*3 {
  26. return fmt.Sprintf("%d weeks", hours/24/7)
  27. } else if hours < 24*365*2 {
  28. return fmt.Sprintf("%d months", hours/24/30)
  29. }
  30. return fmt.Sprintf("%d years", int(d.Hours())/24/365)
  31. }