douciping4283 2017-06-02 23:09
浏览 132
已采纳

如何在Go中将“月dd,yyyy”转换为yyyy-mm-dd?

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条回答 默认 最新

  • douxihui8270 2017-06-02 23:49
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?