Created
May 8, 2023 02:58
-
-
Save brandon-wallace/56506321d8516783a88feb1a452e4d9f to your computer and use it in GitHub Desktop.
Format time.Duration to Days, Hours, and Minutes
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" | |
"time" | |
) | |
// formatTimedelta converts seconds into days, hours, and minutes. | |
func formatTimedelta(t time.Duration) string { | |
seconds := t * time.Second | |
if seconds > 31536000 { | |
return "" | |
} | |
days := int(seconds.Seconds() / 86400) | |
hours := int(seconds.Seconds() / 3600) % 24 | |
minutes := int(seconds.Seconds() / 60) % 60 | |
return fmt.Sprintf("%dd %dh %dm\n", days, hours, minutes) | |
} | |
func main() { | |
fmt.Println(formatTimedelta(964800)) | |
fmt.Println(formatTimedelta(965100)) | |
} | |
// Output | |
// 11d 4h 0m | |
// 11d 4h 5m |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment