Struct std::time::SystemTime
1.8.0 · source · [−]pub struct SystemTime(_);
Expand description
A measurement of the system clock, useful for talking to external entities like the file system or other processes.
Distinct from the Instant
type, this time measurement is not
monotonic. This means that you can save a file to the file system, then
save another file to the file system, and the second file has a
SystemTime
measurement earlier than the first. In other words, an
operation that happens after another operation in real time may have an
earlier SystemTime
!
Consequently, comparing two SystemTime
instances to learn about the
duration between them returns a Result
instead of an infallible Duration
to indicate that this sort of time drift may happen and needs to be handled.
Although a SystemTime
cannot be directly inspected, the UNIX_EPOCH
constant is provided in this module as an anchor in time to learn
information about a SystemTime
. By calculating the duration from this
fixed point in time, a SystemTime
can be converted to a human-readable time,
or perhaps some other string representation.
The size of a SystemTime
struct may vary depending on the target operating
system.
Example:
use std::time::{Duration, SystemTime};
use std::thread::sleep;
fn main() {
let now = SystemTime::now();
// we sleep for 2 seconds
sleep(Duration::new(2, 0));
match now.elapsed() {
Ok(elapsed) => {
// it prints '2'
println!("{}", elapsed.as_secs());
}
Err(e) => {
// an error occurred!
println!("Error: {e:?}");
}
}
}
RunPlatform-specific behavior
The precision of SystemTime
can depend on the underlying OS-specific time format.
For example, on Windows the time is represented in 100 nanosecond intervals whereas Linux
can represent nanosecond intervals.
The following system calls are currently being used by now()
to find out
the current time:
Platform | System call |
---|---|
SGX | insecure_time usercall. More information on timekeeping in SGX |
UNIX | clock_gettime (Realtime Clock) |
Darwin | gettimeofday |
VXWorks | clock_gettime (Realtime Clock) |
SOLID | SOLID_RTC_ReadTime |
WASI | __wasi_clock_time_get (Realtime Clock) |
Windows | GetSystemTimePreciseAsFileTime / GetSystemTimeAsFileTime |
Disclaimer: These system calls might change over time.
Note: mathematical operations like
add
may panic if the underlying structure cannot represent the new point in time.
Implementations
sourceimpl SystemTime
impl SystemTime
1.28.0 · sourcepub const UNIX_EPOCH: SystemTime = UNIX_EPOCH
pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH
An anchor in time which can be used to create new SystemTime
instances or
learn about where in time a SystemTime
lies.
This constant is defined to be “1970-01-01 00:00:00 UTC” on all systems with
respect to the system clock. Using duration_since
on an existing
SystemTime
instance can tell how far away from this point in time a
measurement lies, and using UNIX_EPOCH + duration
can be used to create a
SystemTime
instance to represent another fixed point in time.
Examples
use std::time::SystemTime;
match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
}
Runsourcepub fn now() -> SystemTime
pub fn now() -> SystemTime
sourcepub fn duration_since(
&self,
earlier: SystemTime
) -> Result<Duration, SystemTimeError>
pub fn duration_since(
&self,
earlier: SystemTime
) -> Result<Duration, SystemTimeError>
Returns the amount of time elapsed from an earlier point in time.
This function may fail because measurements taken earlier are not
guaranteed to always be before later measurements (due to anomalies such
as the system clock being adjusted either forwards or backwards).
Instant
can be used to measure elapsed time without this risk of failure.
If successful, Ok(Duration)
is returned where the duration represents
the amount of time elapsed from the specified measurement to this one.
Returns an Err
if earlier
is later than self
, and the error
contains how far from self
the time is.
Examples
use std::time::SystemTime;
let sys_time = SystemTime::now();
let new_sys_time = SystemTime::now();
let difference = new_sys_time.duration_since(sys_time)
.expect("Clock may have gone backwards");
println!("{difference:?}");
Runsourcepub fn elapsed(&self) -> Result<Duration, SystemTimeError>
pub fn elapsed(&self) -> Result<Duration, SystemTimeError>
Returns the difference between the clock time when this system time was created, and the current clock time.
This function may fail as the underlying system clock is susceptible to
drift and updates (e.g., the system clock could go backwards), so this
function might not always succeed. If successful, Ok(Duration)
is
returned where the duration represents the amount of time elapsed from
this time measurement to the current time.
To measure elapsed time reliably, use Instant
instead.
Returns an Err
if self
is later than the current system time, and
the error contains how far from the current system time self
is.
Examples
use std::thread::sleep;
use std::time::{Duration, SystemTime};
let sys_time = SystemTime::now();
let one_sec = Duration::from_secs(1);
sleep(one_sec);
assert!(sys_time.elapsed().unwrap() >= one_sec);
Run1.34.0 · sourcepub fn checked_add(&self, duration: Duration) -> Option<SystemTime>
pub fn checked_add(&self, duration: Duration) -> Option<SystemTime>
Returns Some(t)
where t
is the time self + duration
if t
can be represented as
SystemTime
(which means it’s inside the bounds of the underlying data structure), None
otherwise.
1.34.0 · sourcepub fn checked_sub(&self, duration: Duration) -> Option<SystemTime>
pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime>
Returns Some(t)
where t
is the time self - duration
if t
can be represented as
SystemTime
(which means it’s inside the bounds of the underlying data structure), None
otherwise.
Trait Implementations
sourceimpl Add<Duration> for SystemTime
impl Add<Duration> for SystemTime
sourcefn add(self, dur: Duration) -> SystemTime
fn add(self, dur: Duration) -> SystemTime
Panics
This function may panic if the resulting point in time cannot be represented by the
underlying data structure. See SystemTime::checked_add
for a version without panic.
type Output = SystemTime
type Output = SystemTime
The resulting type after applying the +
operator.
1.9.0 · sourceimpl AddAssign<Duration> for SystemTime
impl AddAssign<Duration> for SystemTime
sourcefn add_assign(&mut self, other: Duration)
fn add_assign(&mut self, other: Duration)
Performs the +=
operation. Read more
sourceimpl Clone for SystemTime
impl Clone for SystemTime
sourcefn clone(&self) -> SystemTime
fn clone(&self) -> SystemTime
Returns a copy of the value. Read more
1.0.0 · sourcefn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source
. Read more
sourceimpl Debug for SystemTime
impl Debug for SystemTime
sourceimpl Hash for SystemTime
impl Hash for SystemTime
sourceimpl Ord for SystemTime
impl Ord for SystemTime
sourceimpl PartialEq<SystemTime> for SystemTime
impl PartialEq<SystemTime> for SystemTime
sourcefn eq(&self, other: &SystemTime) -> bool
fn eq(&self, other: &SystemTime) -> bool
This method tests for self
and other
values to be equal, and is used
by ==
. Read more
sourcefn ne(&self, other: &SystemTime) -> bool
fn ne(&self, other: &SystemTime) -> bool
This method tests for !=
.
sourceimpl PartialOrd<SystemTime> for SystemTime
impl PartialOrd<SystemTime> for SystemTime
sourcefn partial_cmp(&self, other: &SystemTime) -> Option<Ordering>
fn partial_cmp(&self, other: &SystemTime) -> Option<Ordering>
This method returns an ordering between self
and other
values if one exists. Read more
1.0.0 · sourcefn lt(&self, other: &Rhs) -> bool
fn lt(&self, other: &Rhs) -> bool
This method tests less than (for self
and other
) and is used by the <
operator. Read more
1.0.0 · sourcefn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
operator. Read more
sourceimpl Sub<Duration> for SystemTime
impl Sub<Duration> for SystemTime
type Output = SystemTime
type Output = SystemTime
The resulting type after applying the -
operator.
sourcefn sub(self, dur: Duration) -> SystemTime
fn sub(self, dur: Duration) -> SystemTime
Performs the -
operation. Read more
1.9.0 · sourceimpl SubAssign<Duration> for SystemTime
impl SubAssign<Duration> for SystemTime
sourcefn sub_assign(&mut self, other: Duration)
fn sub_assign(&mut self, other: Duration)
Performs the -=
operation. Read more
impl Copy for SystemTime
impl Eq for SystemTime
impl StructuralEq for SystemTime
impl StructuralPartialEq for SystemTime
Auto Trait Implementations
impl RefUnwindSafe for SystemTime
impl Send for SystemTime
impl Sync for SystemTime
impl Unpin for SystemTime
impl UnwindSafe for SystemTime
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> ToOwned for T where
T: Clone,
impl<T> ToOwned for T where
T: Clone,
type Owned = T
type Owned = T
The resulting type after obtaining ownership.
sourcefn clone_into(&self, target: &mut T)
fn clone_into(&self, target: &mut T)
Uses borrowed data to replace owned data, usually by cloning. Read more