Home >Backend Development >Golang >How to Customize Timestamp Formatting in Go's JSON Encoding?
Formatting Timestamps for JSON Encoding
When working with Go, one might encounter a need to format timestamps outputted by the time.Time type. By default, JSON marshals time as RFC3339, resulting in an undesirable format.
Customizing Timestamp Formatting
To customize timestamp formatting, implement the Marshaler interface for your custom time type:
import ( "encoding/json" "fmt" ) type JSONTime time.Time func (t JSONTime) MarshalJSON() ([]byte, error) { stamp := fmt.Sprintf("\"%s\"", time.Time(t).Format("Mon Jan _2")) return []byte(stamp), nil }
Apply this custom type to your Document struct:
type Document struct { Name string Content string Stamp JSONTime Author string }
When marshaling, you can then initialize the Document instance as:
testDoc := model.Document{"Meeting Notes", "These are some notes", JSONTime(time.Now()), "Bacon"}
The resultant JSON will now have a formatted timestamp in your desired format, such as "May 15, 2014".
The above is the detailed content of How to Customize Timestamp Formatting in Go's JSON Encoding?. For more information, please follow other related articles on the PHP Chinese website!