Frammenti di timestamp Unix in Go
Esempi Go per secondi, millisecondi e nanosecondi Unix, conversione di timestamp in time.Time e formattazione con RFC3339 o layout personalizzati.
Go timestamp basics
Go's time package has direct helpers for Unix seconds, milliseconds, and nanoseconds. Use time.Now().Unix() for seconds and time.Now().UnixMilli() for JavaScript-compatible milliseconds.
Formatting time.Time values
Use time.Unix(seconds, 0) to create a time.Time from Unix seconds, then call UTC() when you want deterministic output. RFC3339 is usually the best string format for API responses.
Go production notes
Go's time.Time carries a location, but Unix timestamps always represent a single UTC instant. Normalize timestamps at API and database boundaries, then format with an explicit location when a user or business rule needs local time. This keeps comparisons simple and prevents local server settings from changing output.
- Use time.Now().Unix() for Unix seconds in logs, queues, and database fields
- Use time.Now().UnixMilli() for JavaScript-compatible values
- Use time.Unix(seconds, 0).UTC() before formatting deterministic strings
- Use time.RFC3339 or time.RFC3339Nano for API responses
Frequently checked Go details
- Should I store time.Time or Unix seconds?
- Use time.Time inside Go when you need calendar operations. Store Unix seconds or a database timestamp type when the value must be indexed, queried, or shared with other systems.
- What unit does time.Unix expect?
- time.Unix expects seconds and nanoseconds as separate arguments. If you receive milliseconds, split or convert the value before calling time.Unix.
- How do I verify Go output?
- Format the value with t.UTC().Format(time.RFC3339) and compare it with the timestamp expected by the API, queue, or database column you are writing.