Is there a way to format the output of time.Since() to add days when aplicable, something like:
[days]d[hours]h[minutes]m[seconds]s
The current format seems to use only hours as the maximum unit:
start := time.Unix(1411691219, 0)
diff := time.Since(start)
21132h9m41.714117301s
But I would like to use days instead of hours, in order to obtain something like:
880d12h9m41.7s
I am currently using the following TimeDiff
function to produce the desired output, but wondering if there is an easy/better/native way of achieving this.
package main
import (
"bytes"
"fmt"
"math"
"time"
)
func main() {
start := time.Unix(1411691219, 0)
diff := time.Since(start)
fmt.Printf("diff = %s
", diff)
fmt.Printf("diff = %s
", TimeDiff(start))
}
func TimeDiff(t time.Time) string {
diff := time.Since(t)
days := diff / (24 * time.Hour)
hours := diff % (24 * time.Hour)
minutes := hours % time.Hour
seconds := math.Mod(minutes.Seconds(), 60)
var buffer bytes.Buffer
if days > 0 {
buffer.WriteString(fmt.Sprintf("%dd", days))
}
if hours/time.Hour > 0 {
buffer.WriteString(fmt.Sprintf("%dh", hours/time.Hour))
}
if minutes/time.Minute > 0 {
buffer.WriteString(fmt.Sprintf("%dm", minutes/time.Minute))
}
if seconds > 0 {
buffer.WriteString(fmt.Sprintf("%.1fs", seconds))
}
return buffer.String()
}