UnmarshalJSON Accepts Multiple Time Layouts

Decode timestamps arriving in several formats by trying layouts from strictest to loosest inside UnmarshalJSON and rejecting unknown shapes.

GoData Integrity

Code

gosnippet
53 lines
package main

import (
	"encoding/json"
	"fmt"
	"time"
)

// Event 模拟外部 API:时间字段可能是完整 RFC3339,也可能只有日期
type Event struct {
	Name string    `json:"name"`
	At   EventTime `json:"at"`
}

// 布局从精确到宽松逐个尝试,全部失败才报错
var layouts = []string{
	time.RFC3339,
	"2006-01-02 15:04:05",
	"2006-01-02",
}

type EventTime struct{ time.Time }

func (t *EventTime) UnmarshalJSON(data []byte) error {
	var s string
	if err := json.Unmarshal(data, &s); err != nil {
		return err
	}
	for _, layout := range layouts {
		parsed, err := time.Parse(layout, s)
		if err == nil {
			t.Time = parsed
			return nil
		}
	}
	return fmt.Errorf("unsupported time %q: want RFC3339, datetime or date", s)
}

func main() {
	for _, payload := range []string{
		`{"name":"deploy","at":"2026-11-19T09:30:00Z"}`,
		`{"name":"backup","at":"2026-11-19 02:00:00"}`,
		`{"name":"release","at":"2026-11-19"}`,
		`{"name":"corrupt","at":"19/11/2026"}`,
	} {
		var event Event
		if err := json.Unmarshal([]byte(payload), &event); err != nil {
			fmt.Println("rejected:", err)
			continue
		}
		fmt.Printf("ok: %s at %s\n", event.Name, event.At.Format(time.RFC3339))
	}
}

Inside the snippet

Structurally, expect the functions UnmarshalJSON and main and nothing else.

for _, layout := range layouts is where the per-item work happens. Error handling is inline: 2 places test err != nil and branch immediately.

Caveats

  • Standard-library through and through — paste it in and it runs.
  • There are no exceptions to catch — err return values must be checked at each call site.

Putting it to use

Entry signature: func (t *EventTime) UnmarshalJSON(data []byte) error

Output lines are prefixed (rejected:, ok:), each prefix ties the line to the step that printed it.

Core lines quoted

return fmt.Errorf("unsupported time %q: want RFC3339, datetime or date", s)
for _, layout := range layouts {
	parsed, err := time.Parse(layout, s)
	if err == nil {
		t.Time = parsed
		return nil
	}
}

Interactive Tools for This Topic

FAQ

How do errors reach the caller?
As returned `error` values, checked at 2 sites — callers must branch on `err` before using the other return values. No panics or exceptions in the snippet.
What does UnmarshalJSON Accepts Multiple Time Layouts print when run?
No setup needed: run the file and look for labeled lines like `rejected:`, `ok:` in the output.