模板自定義函數 template function
阿新 • • 發佈:2018-01-01
定義 date sta func pan pre 數據庫 files ()
sqlite3中的日期默認是UTC,當日期字段的默認值是CURRENT_TIMESTAMP時,這個日期和北京時間CST少了8小時。
網上建議說數據庫裏用UTC,讀取數據時再轉換為當地時間。
web頁面中的日期如創建日期通常是需要“格式化”一下的,否則顯示出來是這個樣子:
2017-08-17 08:50:37 +0000 UTC
在go template中可以使用管道,自定義一個日期函數即可。
其實這個函數很簡單,關鍵就是要用Local函數:
func formatDate(t time.Time) string { layout := "2006-01-02" return t.Local().Format(layout) }
還要記住一點:給模板中增加的自定義函數要在解析html文件前調用!
funcMap := template.FuncMap{ "fdate": formatDate, "fdatetime": formatDateTime } t, err := template.New("employees.html").Funcs(funcMap).ParseFiles("employees.html")
-- END --
模板自定義函數 template function