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 或資料庫約定。