xml - Golang 不时解码 mysql 格式。时间

标签 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

最佳答案

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

关于xml - Golang 不时解码 mysql 格式。时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37869600/

相关文章:

android - xml中的按钮点击监听器

xml - Azure B2C : Where to Create DateTime Extension Attribute to be used in Custom Policy- Portal or Custom Policy or Both?

go - 在 Go 中修改导入的库

android - 构建 android-go "stdlib.h: No such file or directory"

go - 多Consumer场景下Go接口(interface)应该在哪里定义?生产者中的界面如何显示通用性?

xml - javax.xml.bind.UnmarshalException : unexpected element (uri :"", 本地 :"sRAssignments")。预期的元素是

java - JAXB 解码返回 null

xml - 在 R 中解析 xml 文件及其元素

java - 如何使用带有字符串输入的 JAXB 2.0 禁用 DTD 获取

android - 在没有此代码的 Android Studio 消息 "Paint.setShadowLayer.. graphics not accurate.."