JSON Structs Carry RFC3339 Timestamps
Carry timestamps in encoding/json through time.Time fields, which parse and emit RFC3339 strings automatically, with time.Parse validating raw stamps.
Code
package main
import (
"encoding/json"
"fmt"
"time"
)
type Commit struct {
Sha string `json:"sha"`
PushedAt time.Time `json:"pushed_at"` // time.Time 按 RFC3339 自动解析与回写
}
func main() {
payload := `{"sha":"9f2ab1c","pushed_at":"2026-11-12T09:30:00Z"}`
var commit Commit
if err := json.Unmarshal([]byte(payload), &commit); err != nil {
fmt.Println("decode:", err)
return
}
fmt.Println("sha:", commit.Sha)
fmt.Println("parsed:", commit.PushedAt.UTC().Format(time.RFC3339))
// Marshal 时 time.Time 同样按 RFC3339 写回字符串,往返不失真
out, _ := json.Marshal(commit)
fmt.Println("round trip:", string(out))
// 裸时间字符串用 time.Parse + time.RFC3339 布局校验
t, err := time.Parse(time.RFC3339, "2026-11-12T17:30:00+08:00")
if err != nil {
fmt.Println("parse:", err)
return
}
fmt.Println("converted to UTC:", t.UTC().Format(time.RFC3339))
// 非法格式会被拒绝
_, err = time.Parse(time.RFC3339, "12/11/2026 09:30")
fmt.Println("invalid rejected:", err != nil)
}What the code does
JSON Structs Carry RFC3339 Timestamps is built around the function main.
Nothing falls through silently — 2 checkpoints test err != nil on the way through.
Applying it
The run emits 7 labeled sections — decode:, sha:, parsed:, round trip:, parse:, converted to UTC:, invalid rejected: — one per step.
Statements that carry the weight
if err != nil {
fmt.Println("parse:", err)
return
}
Interactive Tools for This Topic
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.
FAQ
- What does JSON Structs Carry RFC3339 Timestamps print when run?
- Execute the whole file; each printed line is prefixed with a label like `decode:`, `sha:`, `parsed:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.