Parse Timestamps Across Fallback Layouts

Try a prioritized list of layouts with time.Parse and wrap the last error, so timestamps arriving from different systems parse with one entry point.

GoConfig Management

Code

gosnippet
41 lines
package main

import (
	"fmt"
	"time"
)

// timestamp 字段可能来自不同系统:按优先级逐个布局尝试
var layouts = []string{
	time.RFC3339,
	"2006-01-02 15:04:05",
	"2006-01-02",
}

func parseTimestamp(raw string) (time.Time, error) {
	var lastErr error
	for _, layout := range layouts {
		t, err := time.Parse(layout, raw)
		if err == nil {
			return t, nil
		}
		lastErr = err
	}
	return time.Time{}, fmt.Errorf("unsupported timestamp %q: %w", raw, lastErr)
}

func main() {
	for _, raw := range []string{
		"2026-11-21T09:30:00Z",
		"2026-11-21 09:30:00",
		"2026-11-21",
		"not a date",
	} {
		t, err := parseTimestamp(raw)
		if err != nil {
			fmt.Println("reject:", err)
			continue
		}
		fmt.Println("parsed:", t.Format(time.RFC3339))
	}
}

The flow of the file

Parse Timestamps Across Fallback Layouts keeps everything in the functions parseTimestamp and main.

A single loop drives the file — for _, layout := range layouts. Error handling is inline: 1 place test err != nil and branch immediately.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.
  • There are no exceptions to catch — err return values must be checked at each call site.

Putting it to use

Entry signature: func parseTimestamp(raw string) (time.Time, error)

Printed lines carry labels — reject:, parsed: — when the file runs.

The entry point wires parseTimestamp together — run it once and the whole demo flows.

Core lines

return time.Time{}, fmt.Errorf("unsupported timestamp %q: %w", raw, lastErr)
for _, layout := range layouts {
	t, err := time.Parse(layout, raw)
	if err == nil {
		return t, nil
	}
	lastErr = err
}
if err != nil {
	fmt.Println("reject:", err)
	continue
}

Interactive Tools for This Topic

FAQ

How are errors reported?
By return value: each fallible call hands back an `error`, checked at 1 place here.
What does Parse Timestamps Across Fallback Layouts print when run?
Run it as a complete program — the output lines carry labels such as `reject:`, `parsed:`.