Title here
Summary here
A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Rust.
use std::time::{SystemTime, UNIX_EPOCH};
fn main() {
// Get the current system time
let now = SystemTime::now();
// Print the current time
println!("{:?}", now);
// Get and print the number of seconds since the Unix epoch
let duration = now.duration_since(UNIX_EPOCH).expect("Time went backwards");
println!("{}", duration.as_secs());
// Get and print the number of milliseconds since the Unix epoch
println!("{}", duration.as_millis());
// Get and print the number of nanoseconds since the Unix epoch
println!("{}", duration.as_nanos());
// Convert seconds since the epoch back to SystemTime
let seconds_since_epoch = duration.as_secs();
let time_from_secs = UNIX_EPOCH + std::time::Duration::from_secs(seconds_since_epoch);
println!("{:?}", time_from_secs);
// Convert nanoseconds since the epoch back to SystemTime
let nanos_since_epoch = duration.as_nanos();
let time_from_nanos = UNIX_EPOCH + std::time::Duration::from_nanos(nanos_since_epoch as u64);
println!("{:?}", time_from_nanos);
}
To run the program:
$ cargo run
SystemTime { tv_sec: 1683650000, tv_nsec: 123456789 }
1683650000
1683650000123
1683650000123456789
SystemTime { tv_sec: 1683650000, tv_nsec: 0 }
SystemTime { tv_sec: 1683650000, tv_nsec: 123456789 }
In Rust, we use the std::time::SystemTime
and std::time::UNIX_EPOCH
to work with timestamps. The duration_since
method gives us the time elapsed since the Unix epoch, which we can then convert to seconds, milliseconds, or nanoseconds using the appropriate methods.
To convert back from seconds or nanoseconds to SystemTime
, we add the duration to UNIX_EPOCH
.
Next, we’ll look at another time-related task: time parsing and formatting.