Home >Backend Development >Golang >How to Customize Timestamp Formatting in Go's JSON Responses?
Formatting Timestamps in Outgoing JSON with Time.Time
In Go, when sending a time.Time type as part of a JSON response, it's often desirable to format the timestamp into a desired format instead of the default ISO 8601 format. To achieve this, you can employ the following techniques:
Custom Marshaling and Unmarshaling
The Marshall interface can be implemented by custom types to determine their JSON representation. Likewise, the Unmarshaler interface can be used to control parsing JSON data into custom types. For time.Time, we'll define a JSONTime type that implements MarshalJSON:
type JSONTime time.Time func (t JSONTime) MarshalJSON() ([]byte, error) { // Format the time in the desired format stamp := fmt.Sprintf("\"%s\"", time.Time(t).Format("Mon Jan _2")) return []byte(stamp), nil }
Updating the Document Type
In the Document type, change the Stamp field type to JSONTime:
type Document struct { ... Stamp JSONTime ... }
Example Usage
Now, when initializing the test document:
testDoc := model.Document{ ... Stamp: JSONTime(time.Now()), ... }
The timestamp will be formatted according to the specified format when encoded as JSON:
{ ... "Stamp": "May 15, 2014" ... }
This approach provides flexibility and control over how time stamps are formatted in JSON responses, allowing for customization according to specific requirements.
The above is the detailed content of How to Customize Timestamp Formatting in Go's JSON Responses?. For more information, please follow other related articles on the PHP Chinese website!