github.com/neatlab/neatio@v1.7.3-0.20220425043230-d903e92fcc75/utilities/common/format.go (about) 1 package common 2 3 import ( 4 "fmt" 5 "regexp" 6 "strings" 7 "time" 8 ) 9 10 type PrettyDuration time.Duration 11 12 var prettyDurationRe = regexp.MustCompile(`\.[0-9]+`) 13 14 func (d PrettyDuration) String() string { 15 label := fmt.Sprintf("%v", time.Duration(d)) 16 if match := prettyDurationRe.FindString(label); len(match) > 4 { 17 label = strings.Replace(label, match, match[:4], 1) 18 } 19 return label 20 } 21 22 type PrettyAge time.Time 23 24 var ageUnits = []struct { 25 Size time.Duration 26 Symbol string 27 }{ 28 {12 * 30 * 24 * time.Hour, "y"}, 29 {30 * 24 * time.Hour, "mo"}, 30 {7 * 24 * time.Hour, "w"}, 31 {24 * time.Hour, "d"}, 32 {time.Hour, "h"}, 33 {time.Minute, "m"}, 34 {time.Second, "s"}, 35 } 36 37 func (t PrettyAge) String() string { 38 39 diff := time.Since(time.Time(t)) 40 if diff < time.Second { 41 return "0" 42 } 43 44 result, prec := "", 0 45 46 for _, unit := range ageUnits { 47 if diff > unit.Size { 48 result = fmt.Sprintf("%s%d%s", result, diff/unit.Size, unit.Symbol) 49 diff %= unit.Size 50 51 if prec += 1; prec >= 3 { 52 break 53 } 54 } 55 } 56 return result 57 }