JSON Date/Time Strings to Go time.Time
Handle JSON date and time strings by converting them to Go time.Time fields. Covers ISO 8601 parsing, custom time formats, and timezone handling.
Detailed Explanation
Converting JSON Date Strings to time.Time
Go's encoding/json package automatically parses RFC 3339 / ISO 8601 date strings into time.Time fields. This is the most common date format in JSON APIs.
Example JSON
{
"id": 42,
"title": "Deploy v2.0",
"created_at": "2024-06-15T09:30:00Z",
"updated_at": "2024-06-15T14:22:33+09:00",
"due_date": "2024-07-01"
}
Generated Go Struct
import "time"
type Task struct {
ID int `json:"id"`
Title string `json:"title"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DueDate string `json:"due_date"`
}
What Parses Automatically
The time.Time type supports RFC 3339 out of the box:
"2024-06-15T09:30:00Z"— UTC"2024-06-15T14:22:33+09:00"— with timezone offset
What Requires Custom Handling
Date-only strings like "2024-07-01" do not unmarshal into time.Time automatically. You have two options:
- Keep it as
stringand parse manually withtime.Parse("2006-01-02", s) - Create a custom type with
UnmarshalJSON:
type DateOnly struct {
time.Time
}
func (d *DateOnly) UnmarshalJSON(b []byte) error {
s := strings.Trim(string(b), "\"")
t, err := time.Parse("2006-01-02", s)
if err != nil {
return err
}
d.Time = t
return nil
}
Timezone Awareness
time.Time preserves the timezone from the JSON string. CreatedAt.Location() returns UTC for "Z" suffixed timestamps. Always use .UTC() or .In(loc) for consistent comparisons.
Nullable Timestamps
Use *time.Time for timestamps that can be null:
DeletedAt *time.Time `json:"deleted_at,omitempty"`
Use Case
Every API with timestamps — event logs, audit trails, scheduling systems — needs proper time handling. Using time.Time gives you timezone-aware comparison, formatting, and duration arithmetic out of the box.