Golang unmarshall mysql format time to time.Time

我有一个2016-06-16 22:21:00XML 文档内的格式的时间。


我想用 Golang 解析那个时间。


type Price struct {

    Instrument string `xml:"Instrument"`

    Bid float32 `xml:"Bid"`

    Ask float32 `xml:"Ask"`

    Updated time.Time  `xml:"Updated"`

}


type Prices []Price


var p Prices

err := xml.Unmarshal(body, &p)

if err != nil {

    log.Panicln(err)

}

我的输出错误如下:


panic: parsing time "2016-06-16 20:59:57" as "2006-01-02T15:04:05Z07:00": cannot parse " 20:59:57" as "T"

如何将 mysql 格式的日期时间字符串解组为time.Time?


我已经读到我需要创建一个新的自定义时间来实现time.Time.


type customTime struct {

    time.Time

}


func (c *customTime) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {

    const shortForm = "2016-12-10 01:00:00" // yyyy-mm-dd hh:ii:ss date format

    var v string

    d.DecodeElement(&v, &start)

    parse, err := time.Parse(shortForm, v)

    if err != nil {

        return err

    }

    *c = customTime{parse}

    return nil

}

但是当我这样做时,我收到以下错误。


panic: parsing time "2016-06-16 20:59:57": month out of range


慕尼黑8549860
浏览 170回答 1
1回答

德玛西亚99

你想要const shortForm = "2006-01-02 15:04:05"。这有点奇怪,但是time.Parse理解格式的方式是你必须给出这个特定的时间作为例子。请参阅https://golang.org/src/time/format.go上的评论:// These are predefined layouts for use in Time.Format and Time.Parse.// The reference time used in the layouts is the specific time://    Mon Jan 2 15:04:05 MST 2006// which is Unix time 1136239445. Since MST is GMT-0700,// the reference time can be thought of as//    01/02 03:04:05PM '06 -0700// To define your own format, write down what the reference time would look// like formatted your way; see the values of constants like ANSIC,// StampMicro or Kitchen for examples.您可能可以想象为什么在这里使用预定义的日期很重要……例如,图书馆需要知道您的意思是 01/02 是 1 月 2 日还是 2 月 1 日。有一个预定义的日期(巧妙地构造以避免重复值)可以消除歧义。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go