Skip to content

Instantly share code, notes, and snippets.

@brandon-wallace
Created May 8, 2023 02:58
Show Gist options
  • Save brandon-wallace/56506321d8516783a88feb1a452e4d9f to your computer and use it in GitHub Desktop.
Save brandon-wallace/56506321d8516783a88feb1a452e4d9f to your computer and use it in GitHub Desktop.
Format time.Duration to Days, Hours, and Minutes
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