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.
Code
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 —
errreturn 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
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.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.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
- 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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.