..
How to format Date to JSON in golang
I have a gorm model and it has a Date field. But golang doesn’t have a “pure” date struct, so we use time.Time
.
type OperationPlanningResult struct {
ID uint
PlannedStartedAt time.Time `json:"planned_started_at"`
}
When I marshal it to JSON, this field is like “2006-01-02T00:00:00Z08” and I need to parse it again in frontend.
One way to do it is writing a custom type and providing a custom MarshalJSON function. But I need to write the relative method for gorm because I’m using gorm. Another way is to override the MarshalJSON for the struct.
// FormatDate formats a date. If the t is null, return "null"
func FormatDate(t *time.Time) string {
if t != nil && !t.IsZero() {
return t.Format("2006-01-02")
}
return "null"
}
// MarshalJSON marshal OperationPlanningResult to json.
func (result OperationPlanningResult) MarshalJSON() ([]byte, error) {
type Alias OperationPlanningResult
temp := struct {
Alias
PlannedStartedAt string `json:"planned_started_at"`
}{
Alias: (Alias)(result),
PlannedStartedAt: FormatDate(result.PlannedStartedAt),
}
return json.Marshal(temp)
}
However, if you have a lot of gorm models to use the date field, a custom datatype is preferred.