Skip to content

Instantly share code, notes, and snippets.

@smjure
Forked from harshavardhana/humanize-duration.go
Created November 30, 2022 19:51
Show Gist options
  • Save smjure/6598f9fadcc557efe535dfc4e68029ba to your computer and use it in GitHub Desktop.
Save smjure/6598f9fadcc557efe535dfc4e68029ba to your computer and use it in GitHub Desktop.
humanizeDuration humanizes time.Duration output to a meaningful value - golang's default ``time.Duration`` output is badly formatted and unreadable.
package main
import (
"fmt"
"math"
"time"
)
// humanizeDuration humanizes time.Duration output to a meaningful value,
// golang's default ``time.Duration`` output is badly formatted and unreadable.
func humanizeDuration(duration time.Duration) string {
if duration.Seconds() < 60.0 {
return fmt.Sprintf("%d seconds", int64(duration.Seconds()))
}
if duration.Minutes() < 60.0 {
remainingSeconds := math.Mod(duration.Seconds(), 60)
return fmt.Sprintf("%d minutes %d seconds", int64(duration.Minutes()), int64(remainingSeconds))
}
if duration.Hours() < 24.0 {
remainingMinutes := math.Mod(duration.Minutes(), 60)
remainingSeconds := math.Mod(duration.Seconds(), 60)
return fmt.Sprintf("%d hours %d minutes %d seconds",
int64(duration.Hours()), int64(remainingMinutes), int64(remainingSeconds))
}
remainingHours := math.Mod(duration.Hours(), 24)
remainingMinutes := math.Mod(duration.Minutes(), 60)
remainingSeconds := math.Mod(duration.Seconds(), 60)
return fmt.Sprintf("%d days %d hours %d minutes %d seconds",
int64(duration.Hours()/24), int64(remainingHours),
int64(remainingMinutes), int64(remainingSeconds))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment