get system boot time in seconds in rust

To get the system boot time in seconds in Rust, we need to use the chrono and std libraries. The chrono library provides us with the ability to work with dates and times in Rust. We need to use the SystemTime::now() function provided by the std library to get the current system time. We then subtract the Duration between the current system time and the UNIX epoch time (1970-01-01T00:00:00Z), to get the system boot time in seconds.

Here's the code:

main.rs
use std::time::{Duration, SystemTime};
use chrono::offset::Utc;

fn main() {
   let boot_time = SystemTime::now()
                        .duration_since(SystemTime::UNIX_EPOCH)
                        .unwrap_or_else(|err| err.duration());

   let now = Utc::now();
   println!("System boot time: {} seconds ago.", boot_time.as_secs());
}
340 chars
12 lines

In the above code, we first calculate the boot time using the SystemTime::now() and subtracting the UNIX epoch time. We then convert the boot time to seconds using the Duration::as_secs() function. Finally, we print the boot time in seconds.

This code should work on any platform that Rust supports.

gistlibby LogSnag