Struct SystemTime
pub struct SystemTime(pub(in ::time) SystemTime);
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.
A SystemTime does not count leap seconds.
SystemTime::now()'s behavior around a leap second
is the same as the operating system's wall clock.
The precise behavior near a leap second
(e.g. whether the clock appears to run slow or fast, or stop, or jump)
depends on platform and configuration,
so should not be relied on.
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) => {
// the system clock went backwards!
println!("Great Scott! {e:?}");
}
}
}
Platform-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) |
| WASI | clock_gettime (Realtime Clock) |
| Darwin | clock_gettime (Realtime Clock) |
| VXWorks | clock_gettime (Realtime Clock) |
| SOLID | SOLID_RTC_ReadTime |
| Windows | GetSystemTimePreciseAsFileTime / GetSystemTimeAsFileTime |
Disclaimer: These system calls might change over time.
Note: mathematical operations like
addmay panic if the underlying structure cannot represent the new point in time.
Fields
0: SystemTime
Implementations
impl SystemTime
const UNIX_EPOCH: SystemTime = UNIX_EPOCH;An anchor in time which can be used to create new
SystemTimeinstances or learn about where in time aSystemTimelies.This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with respect to the system clock. Using
duration_sinceon an existingSystemTimeinstance can tell how far away from this point in time a measurement lies, and usingUNIX_EPOCH + durationcan be used to create aSystemTimeinstance to represent another fixed point in time.duration_since(UNIX_EPOCH).unwrap().as_secs()returns the number of non-leap seconds since the start of 1970 UTC. This is a POSIXtime_t(as au64), and is the same time representation as used in many Internet protocols.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!"), }const MAX: SystemTime = _;Represents the maximum value representable by
SystemTimeon this platform.This value differs a lot between platforms, but it is always the case that any positive addition of a
Duration, whose value is greater than or equal to the time precision of the operating system, toSystemTime::MAXwill fail.Examples
#![feature(time_systemtime_limits)] use std::time::{Duration, SystemTime}; // Adding zero will change nothing. assert_eq!(SystemTime::MAX.checked_add(Duration::ZERO), Some(SystemTime::MAX)); // But adding just one second will already fail ... // // Keep in mind that this in fact may succeed, if the Duration is // smaller than the time precision of the operating system, which // happens to be 1ns on most operating systems, with Windows being the // notable exception by using 100ns, hence why this example uses 1s. assert_eq!(SystemTime::MAX.checked_add(Duration::new(1, 0)), None); // Utilize this for saturating arithmetic to improve error handling. // In this case, we will use a certificate with a timestamp in the // future as a practical example. let configured_offset = Duration::from_secs(60 * 60 * 24); let valid_after = SystemTime::now() .checked_add(configured_offset) .unwrap_or(SystemTime::MAX);const MIN: SystemTime = _;Represents the minimum value representable by
SystemTimeon this platform.This value differs a lot between platforms, but it is always the case that any positive subtraction of a
Durationfrom, whose value is greater than or equal to the time precision of the operating system, toSystemTime::MINwill fail.Depending on the platform, this may be either less than or equal to
SystemTime::UNIX_EPOCH, depending on whether the operating system supports the representation of timestamps before the Unix epoch or not. However, it is always guaranteed that aSystemTime::UNIX_EPOCHfits between aSystemTime::MINandSystemTime::MAX.Examples
use ; // Subtracting zero will change nothing. assert_eq!; // But subtracting just one second will already fail. // // Keep in mind that this in fact may succeed, if the Duration is // smaller than the time precision of the operating system, which // happens to be 1ns on most operating systems, with Windows being the // notable exception by using 100ns, hence why this example uses 1s. assert_eq!; // Utilize this for saturating arithmetic to improve error handling. // In this case, we will use a cache expiry as a practical example. let configured_expiry = from_secs; let expiry_threshold = now .checked_sub .unwrap_or;fn now() -> SystemTimeReturns the system time corresponding to "now".
Examples
use SystemTime; let sys_time = now;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).
Instantcan 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
Errifearlieris later thanself, and the error contains how far fromselfthe 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:?}");fn elapsed(&self) -> Result<Duration, SystemTimeError>Returns the difference from this system time to 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
Instantinstead.Returns an
Errifselfis later than the current system time, and the error contains how far from the current system timeselfis.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);fn checked_add(&self, duration: Duration) -> Option<SystemTime>Returns
Some(t)wheretis the timeself + durationiftcan be represented asSystemTime(which means it's inside the bounds of the underlying data structure),Noneotherwise.In the case that the
durationis smaller than the time precision of the operating system,Some(self)will be returned.fn checked_sub(&self, duration: Duration) -> Option<SystemTime>Returns
Some(t)wheretis the timeself - durationiftcan be represented asSystemTime(which means it's inside the bounds of the underlying data structure),Noneotherwise.In the case that the
durationis smaller than the time precision of the operating system,Some(self)will be returned.fn saturating_add(&self, duration: Duration) -> SystemTimeSaturating
SystemTimeaddition, computingself + duration, returningSystemTime::MAXif overflow occurred.In the case that the
durationis smaller than the time precision of the operating system,selfwill be returned.fn saturating_sub(&self, duration: Duration) -> SystemTimeSaturating
SystemTimesubtraction, computingself - duration, returningSystemTime::MINif overflow occurred.In the case that the
durationis smaller than the time precision of the operating system,selfwill be returned.fn saturating_duration_since(&self, earlier: SystemTime) -> DurationSaturating computation of time elapsed from an earlier point in time, returning
Duration::ZEROin the case thatearlieris later or equal toself.Examples
#![feature(time_saturating_systemtime)] use std::time::{Duration, SystemTime}; let now = SystemTime::now(); let prev = now.saturating_sub(Duration::new(1, 0)); // now - prev should return non-zero. assert_eq!(now.saturating_duration_since(prev), Duration::new(1, 0)); assert!(now.duration_since(prev).is_ok()); // prev - now should return zero (and fail with the non-saturating). assert_eq!(prev.saturating_duration_since(now), Duration::ZERO); assert!(prev.duration_since(now).is_err()); // now - now should return zero (and work with the non-saturating). assert_eq!(now.saturating_duration_since(now), Duration::ZERO); assert!(now.duration_since(now).is_ok());
Trait Implementations
impl Add<Duration> for SystemTime
type Output = SystemTime;fn add(self, dur: Duration) -> SystemTimePanics
This function may panic if the resulting point in time cannot be represented by the underlying data structure. See
SystemTime::checked_addfor a version without panic.
impl AddAssign<Duration> for SystemTime
fn add_assign(&mut self, other: Duration)
impl Clone for SystemTime
fn clone(&self) -> SystemTime
impl Copy for SystemTime
impl Debug for SystemTime
fn fmt(&self, f: &mut Formatter<'_>) -> Result
impl Eq for SystemTime
fn assert_fields_are_eq(&self)
impl FromInner<SystemTime> for SystemTime
fn from_inner(time: SystemTime) -> SystemTime
impl Hash for SystemTime
fn hash<__H: Hasher>(&self, state: &mut __H)
impl IntoInner<SystemTime> for SystemTime
fn into_inner(self) -> SystemTime
impl Ord for SystemTime
fn cmp(&self, other: &SystemTime) -> Ordering
impl PartialEq for SystemTime
fn eq(&self, other: &SystemTime) -> bool
impl PartialOrd for SystemTime
fn partial_cmp(&self, other: &SystemTime) -> Option<Ordering>
impl StructuralPartialEq for SystemTime
impl Sub<Duration> for SystemTime
type Output = SystemTime;fn sub(self, dur: Duration) -> SystemTime
impl SubAssign<Duration> for SystemTime
fn sub_assign(&mut self, other: Duration)
impl TrivialClone for SystemTime
Auto Trait Implementations
impl Freeze for SystemTime
impl RefUnwindSafe for SystemTime
impl Send for SystemTime
impl Sync for SystemTime
impl Unpin for SystemTime
impl UnsafeUnpin for SystemTime
impl UnwindSafe for SystemTime
Blanket Implementations
impl<T> Any for SystemTime
where
T: 'static + ?Sized,
fn type_id(&self) -> TypeId
impl<T> Borrow<T> for SystemTime
where
T: ?Sized,
fn borrow(&self) -> &T
impl<T> BorrowMut<T> for SystemTime
where
T: ?Sized,
fn borrow_mut(&mut self) -> &mut T
impl<T> CloneToUninit for SystemTime
where
T: Clone,
unsafe fn clone_to_uninit(&self, dest: *mut u8)
impl<T> From<T> for SystemTime
fn from(t: T) -> TReturns the argument unchanged.
impl<T> Printable for SystemTime
where
T: Copy + Debug,
impl<T> SizeHint for SystemTime
where
T: ?Sized,
fn lower_bound(&self) -> usizefn upper_bound(&self) -> Option<usize>
impl<T> SizedTypeProperties for SystemTime
impl<T> ToOwned for SystemTime
where
T: Clone,
type Owned = T;fn to_owned(&self) -> Tfn clone_into(&self, target: &mut T)
impl<T, U> Into<U> for SystemTime
where
U: From<T>,
fn into(self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom<U> for SystemTime
where
U: Into<T>,
type Error = Infallible;fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto<U> for SystemTime
where
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error;fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>