Rust Unix 时间戳代码片段
Rust 示例,涵盖当前 Unix 秒、毫秒、基于 chrono 的格式化,以及将纪元值转换为可读的 UTC 字符串。
Current Unix timestamp (seconds)
use std::time::{SystemTime, UNIX_EPOCH};
let ts = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();Current Unix timestamp (milliseconds)
use std::time::{SystemTime, UNIX_EPOCH};
let ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis();With the chrono crate
// Cargo.toml: chrono = "0.4"
use chrono::Utc;
Utc::now().timestamp() // seconds
Utc::now().timestamp_millis() // millisecondsFormat with chrono
use chrono::{DateTime, TimeZone, Utc};
let dt: DateTime<Utc> = Utc.timestamp_opt(1700000000, 0).unwrap();
println!("{}", dt.to_rfc3339());
println!("{}", dt.format("%Y-%m-%d %H:%M:%S"));Rust 时间戳基础
标准库公开了 SystemTime 和 UNIX_EPOCH,用于无依赖的时间戳计算。duration_since(UNIX_EPOCH) 可读取为秒、毫秒、微秒或纳秒。
在 Rust 中格式化时间戳
对于可读日期,许多 Rust 项目使用 chrono crate。把纪元秒转换为 UTC DateTime,然后格式化为 RFC3339 或为日志和用户界面定制的字符串。
Rust 生产注意事项
Rust 标准库足以测量时长和读取 Unix 时间,而 chrono 或 time 等 crate 更适合日历格式化。把可能失败的转换放在靠近输入处理的位置,因为外部时间戳可能为负、过大或单位错误。
- 来自 SystemTime 的标准 Unix 秒用 as_secs()
- 与 JavaScript 兼容的时间戳用 as_millis()
- 当你需要解析、带时区的格式化或 RFC3339 输出时,使用 chrono 或 time
- 在把外部时间戳存入带类型的结构体之前,先验证其单位
FAQ
- SystemTime 能处理 1970 年之前的日期吗?
- SystemTime 可以表示 Unix 纪元附近的时刻,但 duration_since(UNIX_EPOCH) 对更早的时刻会返回错误。如果外部时间戳可能为负,请处理这种情况。
- 每个时间戳都需要 chrono 吗?
- 不。对当前的 Unix 秒和毫秒,标准库就够了。当你需要解析、格式化或日历逻辑时,使用 chrono 或 time。
- 如何验证 Rust 的时间戳单位?
- 用 chrono 或 time 把一个样本值转换为 RFC3339,然后在把该字段当作秒或毫秒接受之前,确认它符合 API 或数据库约定。