」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在Golang中將XML列為“時間”字段時指定自定義日期格式?

如何在Golang中將XML列為“時間”字段時指定自定義日期格式?

發佈於2025-03-25
瀏覽:571

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