Type time.Time, Formats and encoding/[xml|json]

943 views
Skip to first unread message

Jev Björsell

unread,
Jun 12, 2013, 12:33:36 PM6/12/13
to golan...@googlegroups.com
Hi All,

I'm looking for a clean & simple approach for dealing with various date/time formats in xml/json when encoding/decoding that data to or from a struct.

The default format produced is ISO 8601. 

If I need to represent my struct in json, and my struct fields of time.Time need to be represented in a format other than ISO 8601 how do I do that?
The same question applies to decoding, I need to receive json/xml that have date/times represented in a format other than ISO 8601. How do I decode that representation and get a populated struct?

I thought there may have been a field tag that would look something like this:
CreatedDateUTC        time.Time `json:"myName,DateFormat(....)"`


Thanks,
-Jev

Chris Hines

unread,
Jun 12, 2013, 8:28:35 PM6/12/13
to golan...@googlegroups.com
Here is one approach that isn't too ugly. I copied the MarshalJSON method from the time package and changed the format string. This new method takes a receiver of a new type that embeds a time.Time. The new type will mostly behave just like a time.Time due to method promotion, except the custom MarshalJSON method hides the one from time.Time, effectively overriding it.


Decoding would require also writing an UnmarshalJSON method in a similar fashion.
Reply all
Reply to author
Forward
0 new messages