Skip to content

Instantly share code, notes, and snippets.

@miquels
Last active November 2, 2022 10:52
Show Gist options
  • Save miquels/abef1b04e09e20b7fec07734496d1f51 to your computer and use it in GitHub Desktop.
Save miquels/abef1b04e09e20b7fec07734496d1f51 to your computer and use it in GitHub Desktop.
Rust SystemTime conversion to unixtime in nanoseconds
trait SystemTimeToUnixTime {
fn unixtime(&self) -> i64;
fn unixtime_ns(&self) -> i64;
}
impl SystemTimeToUnixTime for std::time::SystemTime {
fn unixtime(&self) -> i64 {
match self.duration_since(std::time::SystemTime::UNIX_EPOCH) {
Ok(n) => n.as_secs().try_into().unwrap_or(i64::MAX),
Err(t) => t.duration().as_secs().try_into().map(|t: i64| -t).unwrap_or(i64::MIN),
}
}
fn unixtime_ns(&self) -> i64 {
match self.duration_since(std::time::SystemTime::UNIX_EPOCH) {
Ok(n) => n.as_nanos().try_into().unwrap_or(i64::MAX),
Err(t) => t.duration().as_nanos().try_into().map(|t: i64| -t).unwrap_or(i64::MIN),
}
}
}
fn main() {
use std::time::{SystemTime, Duration};
// let now = SystemTime::now();
let now = SystemTime::UNIX_EPOCH - Duration::from_millis(10543);
println!("seconds since epoch: {}", now.unixtime_ns() as f64 / 1_000_000_000f64);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment