From 68b3ffa79979f4f077599df3a4e1c0b8dfa5e50e Mon Sep 17 00:00:00 2001 From: Luther Wen Xu Date: Sat, 30 May 2020 20:45:01 +0800 Subject: [PATCH] feat: Add ability to format time and plural --- util/format.go | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 util/format.go diff --git a/util/format.go b/util/format.go new file mode 100644 index 0000000..af0dd2b --- /dev/null +++ b/util/format.go @@ -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 +}