add 'ago' or 'from now' to duration string

not great code, should probably refactor this at some point
This commit is contained in:
alyssa rose 2021-04-05 17:41:14 +00:00
parent 6b51cbed6c
commit 4db25fe681
1 changed files with 29 additions and 21 deletions

View File

@ -70,45 +70,53 @@ func displayInteractionCount(c int64) string {
return "" return ""
} }
func DurToStr(dur time.Duration) string { func DurToStr(dur time.Duration, isAgo bool) string {
ret := ""
s := dur.Seconds() s := dur.Seconds()
if s < 60 {
return strconv.Itoa(int(s)) + "s"
}
m := dur.Minutes() m := dur.Minutes()
if m < 60*2 {
return strconv.Itoa(int(m)) + "m"
}
h := dur.Hours() h := dur.Hours()
if h < 24*2 {
return strconv.Itoa(int(h)) + "h"
}
d := h / 24 d := h / 24
if d < 30*2 {
return strconv.Itoa(int(d)) + "d"
}
mo := d / 30 mo := d / 30
if mo < 12*2 {
return strconv.Itoa(int(mo)) + "mo"
}
y := mo / 12 y := mo / 12
return strconv.Itoa(int(y)) + "y"
if s < 60 {
ret = strconv.Itoa(int(s)) + "s"
} else if m < 60*2 {
ret = strconv.Itoa(int(m)) + "m"
} else if h < 24*2 {
ret = strconv.Itoa(int(h)) + "h"
} else if d < 30*2 {
ret = strconv.Itoa(int(d)) + "d"
} else if mo < 12*2 {
ret = strconv.Itoa(int(mo)) + "mo"
} else {
ret = strconv.Itoa(int(y)) + "y"
}
if isAgo {
ret += " ago"
} else {
ret += " from now"
}
return ret
} }
func timeSince(t time.Time) string { func timeSince(t time.Time) string {
d := time.Since(t) d := time.Since(t)
if d < 0 { if d < 0 {
d = 0 return timeUntil(t)
} }
return DurToStr(d) return DurToStr(d, true)
} }
func timeUntil(t time.Time) string { func timeUntil(t time.Time) string {
d := time.Until(t) d := time.Until(t)
if d < 0 { if d < 0 {
d = 0 return timeSince(t)
} }
return DurToStr(d) return DurToStr(d, false)
} }
func formatTimeRFC3339(t time.Time) string { func formatTimeRFC3339(t time.Time) string {