dptgpyl61857413 2015-06-19 01:00
浏览 71
已采纳

如何在Go中将自定义格式的时间序列化到xml中/从xml序列化?

When serializing a datetime to/from xml how do I make it use a custom time format?

  • 写回答

2条回答 默认 最新

  • dst3605528 2015-06-19 14:53
    关注

    Just as you'd implement json.Marshaler and json.Unmarshaler for doing this with JSON (there are many posts about that on StackOverflow and the internet); one way is to implement a custom time type that implements encoding.TextMarshaler and encoding.TextUnmarshaler.

    Those interfaces are used by encoding/xml when encoding items (after first checking for the more specific xml.Marshaler or xml.Unmarshaler interfaces, however those later ones have to do full XML encoding themselves).

    E.g. something like (full example on the <kbd>Go Playground</kbd>):

    const fixedFormat = "Mon Jan 02 2006"
    
    type myTime1 struct {
        time.Time
    }
    
    func (m myTime1) MarshalText() ([]byte, error) {
        text := m.Time.Format(fixedFormat)
        return []byte(text), nil
    }
    func (m *myTime1) UnmarshalText(text []byte) error {
        t, err := time.Parse(fixedFormat, string(text))
        if err == nil {
            m.Time = t
        }
        return err
    }
    

    or

    type myTime2 time.Time
    
    func (m myTime2) MarshalText() ([]byte, error) {
        text := time.Time(m2).Format(fixedFormat)
        return []byte(text), nil
    }
    func (m *myTime2) UnmarshalText(text []byte) error {
        t, err := time.Parse(fixedFormat, string(text))
        if err == nil {
            *m = myTime2(t)
        }
        return err
    }
    

    Either of those can be used in place of time.Time as part of a larger data structure used with xml (un)marshalling. E.g.:

    type Foo struct {
        Date1 myTime1 `xml:"date1"`
        Date2 myTime2 `xml:"date2"`
    }
    

    The difference in how these custom time types are defined changes how you use them with regular time.Time values. E.g.

    m1 := myTime1{time.Now()}
    fmt.Println(m1)
    if m1.Before(time.Now()) {}
    t1 := m1.Time
    // compared to:
    m2 := myTime2(time.Now())
    fmt.Println(time.Time(m2))
    if time.Time(m2).Before(time.Now()) {}
    t2 := time.Time(m2)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含