Golang unmarshall mysql格式的时间。时间

时间:2016-06-16 21:26:36

标签: xml go unmarshalling

我在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

1 个答案:

答案 0 :(得分:1)

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