duankan8739
2017-11-23 07:01
浏览 693
已采纳

将日期从DD-MON-YY转换为YYYYMMDD

In GoLang, how should I convert date from DD-MON-YY to YYYYMMDD format?

My input is: 9-Nov-17
Expected output is: 20171109

But when I do below:

t, err := time.Parse("20060102", "9-Nov-17")

Golang returns error:

Error: parsing time "9-Nov-17" as "20060102": cannot parse "v-17" as "2006"

Please help.

图片转代码服务由CSDN问答提供 功能建议

在GoLang中,如何将日期从DD-MON-YY转换为YYYYMMDD格式?

 我的输入是:2017年11月9日
预期输出是:20171109 
   
 
 

但是当我这样做时

  t,err:= time.Parse(“ 20060102”,“ 9-Nov-17”)
   
 \  n 

Golang返回错误:

 错误:将时间“ 9-Nov-17”解析为“ 20060102”:无法将“ v-17”解析为“ 2006” \  n   
 
 

请帮助。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongping2023 2017-11-23 07:09
    已采纳

    You have to parse the time in the current format and then format it into the expected format using Format function

    Check the answer below

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        // Parse a time value from a string in dd-Mon-yy format.
        t, _ := time.Parse("2-Jan-06", "9-Nov-17")
        //Format and print time in yyyymmdd format
        fmt.Println(t.Format("20060102"))
    }
    

    play link here : goplayground

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • duanqian1888 2017-11-23 07:16

    There something called layout while parsing and formatting time in go. This layout will always formatted based on Mon Jan 2 15:04:05 -0700 MST 2006 time value. As example if you have input 2017 November 22, then the layout should be2006 January 02:

    // example 1          -- layout ---      --- input -----
    t, err := time.Parse("2006 January 02", "2017 November 22")
    // example 2
    t, err := time.Parse("02-01-2006", "22-11-2017")
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题