Golang 解组 mysql 格式化时间为 time.Time

Golang unmarshall mysql format time to time.Time

我在 XML 文档中有 2016-06-16 22:21:00 格式的时间。

我想用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

你想要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 日。有一个预定义的日期(巧妙地构造以避免重复值)消除歧义。