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.

GoData Integrity

Code

gosnippet
39 lines
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

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:`.