How do you convert "Month dd, yyyy" to yyyy-mm-dd in Go?

huangapple go评论96阅读模式
英文:

How do you convert "Month dd, yyyy" to yyyy-mm-dd in Go?

问题

我需要将例如"April 20, 1996"转换为1996-04-20。我尝试了以下代码,但我有一种感觉我在某种程度上是在反向操作。

func main() {
    value := "April 20, 1996"
    layout := "January 1, 1996"
    t, _ := time.Parse(layout, value)
    fmt.Println(t)
    mydate, _ := time.Parse("2006-01-02", "2016-07-08")
    fmt.Println("time:", mydate.Format("April 20, 1996 (MST)"))
}
英文:

I need to convert for example "April 20, 1996" to 1996-04-20. I have tried the following code but I have a feeling that I am doing it in reverse somehow.

func main() {
    value  := "April 20, 1996"
    layout := "January 1, 1996"
    t, _ := time.Parse(layout, value)
    fmt.Println(t)
    mydate, _ := time.Parse("2006-01-02", "2016-07-08")
    fmt.Println("time:", mydate.Format("April 20, 1996 (MST)"))
}

答案1

得分: 2

你只需要使用输入布局解析时间,然后使用输出布局打印时间。布局始终指定参考时间(Mon Jan 2 15:04:05 MST 2006)在给定格式中的显示方式。我认为这就是你想要的:

func main() {
    value := "April 20, 1996"
    layout := "January 2, 2006"
    t, _ := time.Parse(layout, value)
    fmt.Println(t)
    fmt.Println("time:", t.Format("2006-01-02"))
}

更多信息请参考:https://golang.org/pkg/time/

英文:

You just need to parse the time using the input layout and then print it using the output layout. The layout always specifies how the reference time (Mon Jan 2 15:04:05 MST 2006) would look in the given format. I think this is what you want:

func main() {
	value := "April 20, 1996"
	layout := "January 2, 2006"
	t, _ := time.Parse(layout, value)
	fmt.Println(t)
	fmt.Println("time:", t.Format("2006-01-02"))
}

See https://golang.org/pkg/time/ for more information.

huangapple
  • 本文由 发表于 2017年6月3日 07:09:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/44338582.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定