github.com/haraldrudell/parl@v0.4.176/ptime/duration.go (about) 1 /* 2 © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package ptime 7 8 import ( 9 "strconv" 10 "time" 11 ) 12 13 // Duration formats time.Duration to string with 2 digits precision or better. 14 // - Duration is more readable than time.Duration.String() that has full ns precision. 15 // - max precision is ns for < 10 µs 16 // - min precision is day for >= 10 days 17 // - units: ns µs ms s m h d “17h27m” 18 // - subsecond digits are rounded with halfway-value rounded away from zero 19 // - second and larger values is truncate 20 func Duration(d time.Duration) (printableDuration string) { 21 var absValue time.Duration 22 if d >= 0 { 23 absValue = d 24 } else { 25 absValue = -d 26 } 27 if absValue < 10*time.Microsecond { 28 return d.String() // ns full precision 314ns 29 } else if absValue < 10*time.Millisecond { 30 return d.Round(time.Microsecond).String() // µs 314µs 31 } else if absValue < 1*time.Second { 32 return d.Round(time.Millisecond).String() // ms 314ms 33 } else if absValue < 10*time.Second { 34 return d.Round(100 * time.Millisecond).String() // 10s 3.1s 35 } else if absValue < 10*time.Minute { 36 return d.Truncate(time.Second).String() // s 31s 37 } else if absValue < 10*time.Hour { 38 return d.Truncate(time.Second).String() // min 5m14s 39 } else if absValue < 24*time.Hour { 40 d = d.Truncate(time.Minute) // h 17h27m 41 return strconv.Itoa(int(d.Hours())) + "h" + strconv.Itoa(int(d.Minutes())%60) + "m" 42 } else if absValue < 240*time.Hour { 43 d = d.Truncate(time.Hour) // days 3d15h 44 return strconv.Itoa(int(d.Hours())/24) + "d" + strconv.Itoa(int(d.Hours())%24) + "h" 45 } 46 d = d.Truncate(24 * time.Hour) // 10+ days 47 return strconv.Itoa(int(d.Hours())/24) + "d" // months 36d years 3636d 48 }