Created
September 13, 2015 09:19
-
-
Save harshavardhana/327e0577c4fed9211f65 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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Thank yaw sir ❤️