Milen/util/format.go

79 lines
1.7 KiB
Go

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
}
2020-05-30 13:31:50 +07:00
func FormatRomanNumeral(number int) string {
if number < 1 || number > 3999 {
return strconv.Itoa(number)
}
conversions := []struct {
value int
digit string
}{
{1000, "M"},
{900, "CM"},
{500, "D"},
{400, "CD"},
{100, "C"},
{90, "XC"},
{50, "L"},
{40, "XL"},
{10, "X"},
{9, "IX"},
{5, "V"},
{4, "IV"},
{1, "I"},
}
roman := ""
for _, conversion := range conversions {
for number >= conversion.value {
roman += conversion.digit
number -= conversion.value
}
}
return roman
}