Skip to content

Instantly share code, notes, and snippets.

@emad-elsaid
Last active June 19, 2022 23:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emad-elsaid/cc026f69d1d73cdb9d87eb3e8931c7d1 to your computer and use it in GitHub Desktop.
Save emad-elsaid/cc026f69d1d73cdb9d87eb3e8931c7d1 to your computer and use it in GitHub Desktop.
Converts a time duration to string. for example: 38 minutes 53 seconds ago OR 2 days 58 minutes ago. maxPrecision is the max number of time components in the result.
func ago(t time.Duration) (o string) {
const day = time.Hour * 24
const week = day * 7
const month = day * 30
const year = day * 365
const maxPrecision = 2
if t.Seconds() < 1 {
return "seconds ago"
}
for precision := 0; t.Seconds() > 0 && precision < maxPrecision; precision++ {
switch {
case t >= year:
years := t / year
t -= years * year
o += fmt.Sprintf("%d years ", years)
case t >= month:
months := t / month
t -= months * month
o += fmt.Sprintf("%d months ", months)
case t >= week:
weeks := t / week
t -= weeks * week
o += fmt.Sprintf("%d weeks ", weeks)
case t >= day:
days := t / day
t -= days * day
o += fmt.Sprintf("%d days ", days)
case t >= time.Hour:
hours := t / time.Hour
t -= hours * time.Hour
o += fmt.Sprintf("%d hours ", hours)
case t >= time.Minute:
minutes := t / time.Minute
t -= minutes * time.Minute
o += fmt.Sprintf("%d minutes ", minutes)
case t >= time.Second:
seconds := t / time.Second
t -= seconds * time.Second
o += fmt.Sprintf("%d seconds ", seconds)
}
}
return o + "ago"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment