您好,我似乎找不到任何能帮助我的东西。
我正在使用格式字符串“January 02, 2006”和时间字符串“2016-07-08”。
然而,当我使用这些参数运行格式时,我得到的响应是2016年7月7日。正确的响应应该是2016年7月8日。
值得注意的是,我也试图通过Sprig来使用它。
{{ date "January 02, 2006" .MyDate }}
如果我能得到任何帮助,将不胜感激。
由于时区的影响,您得到了正确的日期,但是 sprig
默认使用 "Local" 格式,而 golang.org/pkg/time
默认使用 "UTC" 格式。
以下是示例代码:(为简单起见省略错误处理)
func main() {
// using the "time" package
mydate, _ := time.Parse("2006-01-02", "2016-07-08")
fmt.Println("time:", mydate.In(time.Local).Format("January 02, 2006 (MST)"), "-- specify Local time zone")
fmt.Println("time:", mydate.Format("January 02, 2006 (MST)"), "-- defaults to UTC")
d := struct{ MyDate time.Time }{mydate}
//using sprig
fmap := sprig.TxtFuncMap()
localTpl := `sprig: {{ date "January 02, 2006 (MST)" .MyDate }} -- defaults to Local`
t := template.Must(template.New("test").Funcs(fmap).Parse(localTpl))
var localdate bytes.Buffer
t.Execute(&localdate, d)
fmt.Println(localdate.String())
utcTpl := `sprig: {{ dateInZone "January 02, 2006 (MST)" .MyDate "UTC"}} -- specify UTC time zone`
t = template.Must(template.New("test").Funcs(fmap).Parse(utcTpl))
var utcdate bytes.Buffer
t.Execute(&utcdate, d)
fmt.Println(utcdate.String())
}
输出:
time: July 07, 2016 (EDT) -- specify Local time zone
time: July 08, 2016 (UTC) -- defaults to UTC
sprig: July 07, 2016 (EDT) -- defaults to Local
sprig: July 08, 2016 (UTC) -- specify UTC time zone
以下是参考资料:
time: https://golang.org/pkg/time
如果没有时区指示符,Parse将返回UTC时间。
spig: https://github.com/Masterminds/sprig/blob/master/functions.go#L407
func date(fmt string, date interface{}) string {
return dateInZone(fmt, date, "Local")
}
注意:如果您想格式化为特定的时区,请查看第二个模板:
utcTpl := `sprig: {{ dateInZone "January 02, 2006 (MST)" .MyDate "UTC"}} -- specify UTC time zone`
我认为正确的方法是将time.Time
类型发送到您的模板,然后在其上使用Format
函数。您可以使用ParseTime
来解析您的2016-07-08
格式。
type Data struct {
CreatedOn time.Time
}
template.Execute(w, Data{})
模板:
<span>{{ .CreatedOn.Format "January 02, 2006" }}</span>