嗨,所以我似乎找不到任何可以帮助我的东西。
我正在使用格式字符串“2006 年 1 月 2 日”和时间字符串“2016-07-08”
但是,当我使用这些参数运行格式时,我得到的响应是 2016 年 7 月 7 日。正确的响应是 2016 年 7 月 8 日。
请注意,我也试图通过 Sprig 使用它。
{{ date "January 02, 2006" .MyDate }}
Run Code Online (Sandbox Code Playgroud)
如果我能得到任何帮助,将不胜感激
这是因为时区的原因,您获得了正确的日期,但默认sprig格式为“本地”,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())
}
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
这里有一些参考:
时间:https : //golang.org/pkg/time
在没有时区指示器的情况下,Parse 返回一个 UTC 时间。
尖刺:https : //github.com/Masterminds/sprig/blob/master/functions.go#L407
func date(fmt string, date interface{}) string {
return dateInZone(fmt, date, "Local")
}
Run Code Online (Sandbox Code Playgroud)
注意:如果要格式化为特定时区,请查看第二个模板:
utcTpl := `sprig: {{ dateInZone "January 02, 2006 (MST)" .MyDate "UTC"}} -- specify UTC time zone`
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10161 次 |
| 最近记录: |