Golang - 解析YYYY-MM-DD日期格式

7

您好,我似乎找不到任何能帮助我的东西。

我正在使用格式字符串“January 02, 2006”和时间字符串“2016-07-08”。

然而,当我使用这些参数运行格式时,我得到的响应是2016年7月7日。正确的响应应该是2016年7月8日。

值得注意的是,我也试图通过Sprig来使用它。

{{ date "January 02, 2006" .MyDate }}

如果我能得到任何帮助,将不胜感激。

可能是时区转换为UTC的问题。 - John S Perayil
2个回答

12

由于时区的影响,您得到了正确的日期,但是 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`

非常感谢。这是深入而有用的内容。由于这个,我解决了我的问题。结果代码: {{ dateInZone "January 02, 2006 (MST)" .Date "UTC"}} 谢谢 - 我不知道如何将您的问题标记为答案 :S。 - user1977351
太棒了,很高兴能帮到你。祝你好运 :) .. 我看到你已经标记了它.. 谢谢。 - davidcv5

2

我认为正确的方法是将time.Time类型发送到您的模板,然后在其上使用Format函数。您可以使用ParseTime来解析您的2016-07-08格式。

type Data struct {
    CreatedOn time.Time
}

template.Execute(w, Data{})

模板:

<span>{{ .CreatedOn.Format "January 02, 2006" }}</span>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接