Unix Timestamps With SystemTime And Duration
Convert between epoch offsets and unix seconds with duration_since, which returns Err instead of a negative duration when the clock runs backwards.
Code
use std::time::{Duration, SystemTime, UNIX_EPOCH};
fn main() {
// 固定时刻演示换算:epoch + 17 亿秒
let deploy = UNIX_EPOCH + Duration::from_secs(1_700_000_000);
let elapsed = deploy.duration_since(UNIX_EPOCH).expect("after epoch");
println!("unix seconds: {}", elapsed.as_secs());
// 反向:从秒数重建 SystemTime 并比较
let restored = UNIX_EPOCH + Duration::from_secs(elapsed.as_secs());
println!("roundtrip: {}", restored == deploy);
// 时钟回拨到 epoch 之前:duration_since 返回 Err 而不是负数
let backdated = UNIX_EPOCH - Duration::from_secs(3600);
match backdated.duration_since(UNIX_EPOCH) {
Ok(_) => println!("unexpected success"),
Err(err) => println!("clock error: {err}"),
}
}Epoch arithmetic
UNIX_EPOCH + Duration::from_secs(1_700_000_000) builds a fixed instant; duration_since(UNIX_EPOCH) converts it back to unix seconds for printing. Restoring via another Duration addition roundtrips to equality (roundtrip: true).
Clock going backwards
UNIX_EPOCH - Duration::from_secs(3600) sits before the epoch. duration_since returns Err for that comparison rather than a negative Duration — the match prints clock error: … and the branch must be handled explicitly.
Why Err instead of negative
Duration is unsigned by design; the API surface turns out-of-order comparisons into a Result so the “before” case cannot masquerade as a value.
Interactive Tools for This Topic
FAQ
- Why does duration_since return Err instead of a negative duration?
- Duration is unsigned; comparing an earlier time against a later one has no representable value, so the API surfaces it as an Err to handle explicitly.
- How does the demo verify the conversion round-trips?
- It rebuilds the instant from the printed seconds (UNIX_EPOCH + Duration::from_secs(...)) and compares with the original, printing roundtrip: true.
Report a problem with this exampleOpens a pre-filled issue on GitHub.