The default time.Duration String method formats the duration with adding 0s
for minutes and 0m0s
for hours. Is there function that I can use that will produce 5m
instead 5m0s
and 2h
instead 2h0m0s
... or I have to implement my own?
Time duration to string 2h instead 2h0m0s
22.8k views Asked by gsf At
2
There are 2 answers
0
On
You can just round the duration like this:
func RountTime(roundTo string, value time.Time) string {
since := time.Since(value)
if roundTo == "h" {
since -= since % time.Hour
}
if roundTo == "m" {
since -= since % time.Minute
}
if roundTo == "s" {
since -= since % time.Second
}
return since.String()
}
Foreword: I released this utility in
github.com/icza/gox
, seetimex.ShortDuration()
.Not in the standard library, but it's really easy to create one:
Testing it:
Output (try it on the Go Playground):