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