英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论