Comment on page
12-Dates-And-Times
在本章,我们将讨论下 Go 处理日期和时间的方法,以及优化 User 及 Post 对象中的时间对象
Flask-Mega 主要是用了它灵活的模板功能,以及 Moment.js 来在前端实现了时间日期的优化,与之不同,我们主要采用的是后端来实现同样的功能
model/user.go
...
// FormattedLastSeen func
func (u *User) FormattedLastSeen() string {
return u.LastSeen.Format("2006-01-02 15:04:05")
}
...
templates/content/profile.html
...
<p>Last seen on: {{ .ProfileUser.FormattedLastSeen }}</p>
...
Notice: 虽然我也比较喜欢其他语言的 %Y-%m-%d %H:%M:%S" layout 形式,但是无奈 Go 就是 "2006-01-02 15:04:05" 这样的layout,没有道理可讲,我有时候甚至怕它搞错 01 和 02 哪个是月 哪个表示 日

12-01
我们目标是显示成
user said 35 minutes ago: post message
这样的形式,这就需要我们对时间日期进行转换简单点,我们就在 utils.go 中实现一个
FromTime
函数model/utils.go
...
const (
minute = 1
hour = minute * 60
day = hour * 24
month = day * 30
year = day * 365
quarter = year / 4
)
// FromDuration returns a friendly string representing an approximation of the
// given duration
func FromDuration(d time.Duration) string {
seconds := round(d.Seconds())
if seconds < 30 {
return "less than a minute"
}
if seconds < 90 {
return "1 minute"
}
minutes := div(seconds, 60)