//根据时间戳计算与当前时间的间距及格式化单位
func FormatDate(in string) (out string) {
timeUnix := time.Now().Unix() //当前时间戳
inn, _ := strconv.ParseInt(in, 10, 64)
outt := timeUnix - inn
f := map[string]string{
"1": "秒",
"60": "分钟",
"3600": "小时",
"86400": "天",
"604800": "星期",
"2592000": "个月",
"31536000": "年",
}
var keys []string
for k := range f {
keys = append(keys, k)
}
//sort.Strings(keys)
//数字字符串 排序
sort.Slice(keys, func(i, j int) bool {
numA, _ := strconv.Atoi(keys[i])
numB, _ := strconv.Atoi(keys[j])
return numA < numB
})
for _, k := range keys {
v2, _ := strconv.Atoi(k)
cc := math.Floor(float64(int(outt) / int(v2)))
if 0 != cc {
out = strconv.FormatFloat(cc, 'f', -1, 64) + f[k] + "前"
}
}
return
}
For implementation details, visit my blog.
Top comments (0)