feat: Add ability to format time and plural
parent
c811aa4334
commit
68b3ffa799
@ -0,0 +1,46 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func FormatTime(seconds int64) string {
|
||||
listedTime := make([]string, 0, 5)
|
||||
if seconds > 365*24*60*60 {
|
||||
listedTime = append(listedTime, FormatPlural(seconds/365/24/60/60, "year", "years"))
|
||||
seconds %= 365 * 24 * 60 * 60
|
||||
}
|
||||
if seconds > 24*60*60 {
|
||||
listedTime = append(listedTime, FormatPlural(seconds/24/60/60, "day", "days"))
|
||||
seconds %= 24 * 60 * 60
|
||||
}
|
||||
if seconds > 60*60 {
|
||||
listedTime = append(listedTime, FormatPlural(seconds/60/60, "hour", "hours"))
|
||||
seconds %= 60 * 60
|
||||
}
|
||||
if seconds > 60 {
|
||||
listedTime = append(listedTime, FormatPlural(seconds/60, "minute", "minutes"))
|
||||
seconds %= 60
|
||||
}
|
||||
listedTime = append(listedTime, FormatPlural(seconds, "second", "seconds"))
|
||||
switch len(listedTime) {
|
||||
case 1:
|
||||
return listedTime[0]
|
||||
case 2:
|
||||
return listedTime[0] + " and " + listedTime[1]
|
||||
}
|
||||
time := ""
|
||||
for i := 0; i < len(listedTime)-2; i++ {
|
||||
time += listedTime[i] + ", "
|
||||
}
|
||||
time += listedTime[len(listedTime)-2] + ", and "
|
||||
time += listedTime[len(listedTime)-1]
|
||||
return time
|
||||
}
|
||||
|
||||
func FormatPlural(count int64, singular string, plural string) string {
|
||||
if count == 0 || count == 1 {
|
||||
return strconv.FormatInt(count, 10) + " " + singular
|
||||
}
|
||||
return strconv.FormatInt(count, 10) + " " + plural
|
||||
}
|
Loading…
Reference in New Issue