”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何在Golang中将XML列为“时间”字段时指定自定义日期格式?

如何在Golang中将XML列为“时间”字段时指定自定义日期格式?

发布于2025-03-25
浏览:211

How to Specify a Custom Date Format When Unmarshaling XML into a `time.Time` Field in Golang? 
克服日期格式的格式差异在Golang Xml unmarshal中使用time.time.time

通过REST APIS SPESSE检索XML数据在试图将golang the Golang the Golang und the Golang uncer the the the the glang the golang结构中提出挑战。当API返回的日期格式与默认时间不符时,出现了一个频繁的问题。TimeParse格式,导致失败的失败。

在这种情况下,诱人的选择是使用字符串来表示DateTime字段,但保持正确定义的类型。要解决此问题,该问题探讨了是否有一种方法可以指定自定义日期格式,当将自定义的日期格式删除到time.time字段中。 要克服此限制,我们可以定义一个新的自定义结构类型来包装时间。Time字段并实现了我们自己的Unmarshalxml方法。此方法将使用我们所需的格式解析XML Date String,并相应地设置基础时间。 // ... dateentred customTime`xml:“ enterdate”`//使用实现umarshalxml的自定义类型 // ... } 键入自定义时间struct { 时间。时间 } func(c *customTime)umarshalxml(d *xml.decoder,start xml.startelement)错误{ const shortform =“ 20060102” // yyyymmdd日期格式 var v字符串 d.decodeelement(& v,start) 解析,err:= time.parse(Shortform,v) 如果err!= nil { 返回错误 } *c =自定义时间{parse} 返回无 }

通过利用此自定义umarshalxml方法,我们可以有效地指定我们自己的日期格式,并确保在删除XML数据时正确填充时间字段。以类似的方式unmarshalxmlattr。

为了进一步参考,提供的GO Playgrogn演示了实现:http://play.golang.org.org/p/efxznsje4a [&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&华

最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3