Human-readable date formats
人类可读的日期格式化
(1) 格式化目标:
将时间戳或日期字符串转成人类友好的时间字符串:比如 “6分钟前” “7小时前”,“8天前”,“9月前” 。。。
(2) utils/human_time.go
代码如下:
package utils
import (
"fmt"
"time"
)
// 将时间字符串转成可读性友好的时间字符串
func Str2HumanTime(datetime string) string {
localTime, _ := time.ParseInLocation("2006-01-02 15:04:05", datetime, time.Local)
res := localTime.Unix()
return HumanTime(res)
}
// 获取可读性友好的时间字符串
func HumanTime(timestamp int64) string {
const minute = 60 // 60 秒
const hour = 3600 // 3600 秒
const day = hour * 24
const week = day * 7
const month = day * 30
const year = month * 12
var now = time.Now().Unix() // 获取当前时间戳
var diff = now - timestamp // 给的日期与当前时间戳的差值
var str string
if diff > year {
str = fmt.Sprintf("%.0f 年前", float64(diff / year))
} else if diff > month {
str = fmt.Sprintf("%.0f 月前", float64(diff / month))
} else if diff > week {
str = fmt.Sprintf("%.0f 周前", float64(diff / week))
} else if diff > day {
str = fmt.Sprintf("%.0f 天前", float64(diff / day))
} else if diff > hour {
str = fmt.Sprintf("%.0f 小时前", float64(diff / hour))
} else if diff > minute {
str = fmt.Sprintf("%.0f 分钟前", float64(diff / minute))
} else if diff > 1000 {
str = fmt.Sprintf("%.0f 秒前", float64(diff / 1000))
} else {
str = "刚刚"
}
return result
}
(3) 测试一下
utils/human_time_test.go
package utils
import (
"testing"
"time"
)
// go test -v utils/human_time_test.go utils/human_time.go
func TestHumanTime(t *testing.T) {
t.Log("---> TestHumanTime")
// var timestamp int64 = 1625882650
timestamp := time.Now().Unix() - 3600*24*66
str := HumanTime(timestamp)
t.Log("---> TestHumanTime", str)
}
func TestStr2HumanTime(t *testing.T) {
t.Log("---> TestStr2HumanTime")
data := "2021-02-06 06:25:56"
str := Str2HumanTime(data)
t.Log("---> TestStr2HumanTime", str)
}
(4) 执行测试文件:
$ go test -v utils/human_time_test.go utils/human_time.go
=== RUN TestHumanTime
human_time_test.go:11: ---> TestHumanTime
human_time_test.go:15: ---> TestHumanTime 2 月前
--- PASS: TestHumanTime (0.00s)
=== RUN TestStr2HumanTime
human_time_test.go:19: ---> TestStr2HumanTime
human_time_test.go:25: ---> TestStr2HumanTime 6 月前
--- PASS: TestStr2HumanTime (0.00s)
PASS
ok command-line-arguments 0.105s
➜ go-gin-api git:(master) ✗
(5) 参考资料:
综合网络
[END]