Rust Unix 时间戳代码片段
Rust 示例,涵盖当前 Unix 秒、毫秒、基于 chrono 的格式化,以及将纪元值转换为可读的 UTC 字符串。
Rust timestamp basics
The standard library exposes SystemTime and UNIX_EPOCH for dependency-free timestamp calculations. duration_since(UNIX_EPOCH) can be read as seconds, milliseconds, microseconds, or nanoseconds.
Formatting timestamps in Rust
For human-readable dates, many Rust projects use the chrono crate. Convert epoch seconds to a UTC DateTime, then format as RFC3339 or a custom string for logs and user interfaces.
Rust production notes
Rust's standard library is enough for measuring durations and reading Unix time, while crates such as chrono or time are better for calendar formatting. Keep fallible conversion close to input handling, because external timestamps can be negative, too large, or expressed in the wrong unit.
- Use as_secs() for standard Unix seconds from SystemTime
- Use as_millis() for JavaScript-compatible timestamps
- Use chrono or time when you need parsing, timezone-aware formatting, or RFC3339 output
- Validate external timestamp units before storing them in typed structs
Frequently checked Rust details
- Can SystemTime handle dates before 1970?
- SystemTime can represent times around the Unix epoch, but duration_since(UNIX_EPOCH) returns an error for earlier instants. Handle that case if external timestamps may be negative.
- Do I need chrono for every timestamp?
- No. The standard library is enough for current Unix seconds and milliseconds. Use chrono or time when you need parsing, formatting, or calendar logic.
- How do I verify Rust timestamp units?
- Convert one sample value to RFC3339 with chrono or time, then confirm it matches the API or database contract before accepting the field as seconds or milliseconds.