Movatterモバイル変換


[0]ホーム

URL:


std::time

StructSystemTime

1.8.0 ·Source
pub struct SystemTime(/* private fields */);
Expand description

A measurement of the system clock, useful for talking toexternal entities like the file system or other processes.

Distinct from theInstant type, this time measurementis notmonotonic. This means that you can save a file to the file system, thensave another file to the file system,and the second file has aSystemTime measurement earlier than the first. In other words, anoperation that happens after another operation in real time may have anearlierSystemTime!

Consequently, comparing twoSystemTime instances to learn about theduration between them returns aResult instead of an infallibleDurationto indicate that this sort of time drift may happen and needs to be handled.

Although aSystemTime cannot be directly inspected, theUNIX_EPOCHconstant is provided in this module as an anchor in time to learninformation about aSystemTime. By calculating the duration from thisfixed point in time, aSystemTime can be converted to a human-readable time,or perhaps some other string representation.

The size of aSystemTime struct may vary depending on the target operatingsystem.

ASystemTime does not count leap seconds.SystemTime::now()’s behavior around a leap secondis 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:

usestd::time::{Duration, SystemTime};usestd::thread::sleep;fnmain() {letnow = SystemTime::now();// we sleep for 2 secondssleep(Duration::new(2,0));matchnow.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 ofSystemTime can depend on the underlying OS-specific time format.For example, on Windows the time is represented in 100 nanosecond intervals whereas Linuxcan represent nanosecond intervals.

The following system calls arecurrently being used bynow() to find outthe current time:

Disclaimer: These system calls might change over time.

Note: mathematical operations likeadd may panic if the underlyingstructure cannot represent the new point in time.

Implementations§

Source§

implSystemTime

1.28.0 ·Source

pub constUNIX_EPOCH:SystemTime = UNIX_EPOCH

An anchor in time which can be used to create newSystemTime instances orlearn about where in time aSystemTime lies.

This constant is defined to be “1970-01-01 00:00:00 UTC” on all systems withrespect to the system clock. Usingduration_since on an existingSystemTime instance can tell how far away from this point in time ameasurement lies, and usingUNIX_EPOCH + duration can be used to create aSystemTime instance to represent another fixed point in time.

duration_since(UNIX_EPOCH).unwrap().as_secs() returnsthe 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
usestd::time::SystemTime;matchSystemTime::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!"),}
1.8.0 ·Source

pub fnnow() ->SystemTime

Returns the system time corresponding to “now”.

§Examples
usestd::time::SystemTime;letsys_time = SystemTime::now();
1.8.0 ·Source

pub fnduration_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 notguaranteed to always be before later measurements (due to anomalies suchas 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 representsthe amount of time elapsed from the specified measurement to this one.

Returns anErr ifearlier is later thanself, and the errorcontains how far fromself the time is.

§Examples
usestd::time::SystemTime;letsys_time = SystemTime::now();letnew_sys_time = SystemTime::now();letdifference = new_sys_time.duration_since(sys_time)    .expect("Clock may have gone backwards");println!("{difference:?}");
1.8.0 ·Source

pub fnelapsed(&self) ->Result<Duration,SystemTimeError>

Returns the difference from this system time to thecurrent clock time.

This function may fail as the underlying system clock is susceptible todrift and updates (e.g., the system clock could go backwards), so thisfunction might not always succeed. If successful,Ok(Duration) isreturned where the duration represents the amount of time elapsed fromthis time measurement to the current time.

To measure elapsed time reliably, useInstant instead.

Returns anErr ifself is later than the current system time, andthe error contains how far from the current system timeself is.

§Examples
usestd::thread::sleep;usestd::time::{Duration, SystemTime};letsys_time = SystemTime::now();letone_sec = Duration::from_secs(1);sleep(one_sec);assert!(sys_time.elapsed().unwrap() >= one_sec);
1.34.0 ·Source

pub fnchecked_add(&self, duration:Duration) ->Option<SystemTime>

ReturnsSome(t) wheret is the timeself + duration ift can be represented asSystemTime (which means it’s inside the bounds of the underlying data structure),Noneotherwise.

1.34.0 ·Source

pub fnchecked_sub(&self, duration:Duration) ->Option<SystemTime>

ReturnsSome(t) wheret is the timeself - duration ift can be represented asSystemTime (which means it’s inside the bounds of the underlying data structure),Noneotherwise.

Trait Implementations§

1.8.0 ·Source§

implAdd<Duration> forSystemTime

Source§

fnadd(self, dur:Duration) ->SystemTime

§Panics

This function may panic if the resulting point in time cannot be represented by theunderlying data structure. SeeSystemTime::checked_add for a version without panic.

Source§

typeOutput =SystemTime

The resulting type after applying the+ operator.
1.9.0 ·Source§

implAddAssign<Duration> forSystemTime

Source§

fnadd_assign(&mut self, other:Duration)

Performs the+= operation.Read more
1.8.0 ·Source§

implClone forSystemTime

Source§

fnclone(&self) ->SystemTime

Returns a copy of the value.Read more
1.0.0 ·Source§

fnclone_from(&mut self, source: &Self)

Performs copy-assignment fromsource.Read more
1.8.0 ·Source§

implDebug forSystemTime

Source§

fnfmt(&self, f: &mutFormatter<'_>) ->Result

Formats the value using the given formatter.Read more
1.8.0 ·Source§

implHash forSystemTime

Source§

fnhash<__H:Hasher>(&self, state:&mut __H)

Feeds this value into the givenHasher.Read more
1.3.0 ·Source§

fnhash_slice<H>(data: &[Self], state:&mut H)
where H:Hasher, Self:Sized,

Feeds a slice of this type into the givenHasher.Read more
1.8.0 ·Source§

implOrd forSystemTime

Source§

fncmp(&self, other: &SystemTime) ->Ordering

This method returns anOrdering betweenself andother.Read more
1.21.0 ·Source§

fnmax(self, other: Self) -> Self
where Self:Sized,

Compares and returns the maximum of two values.Read more
1.21.0 ·Source§

fnmin(self, other: Self) -> Self
where Self:Sized,

Compares and returns the minimum of two values.Read more
1.50.0 ·Source§

fnclamp(self, min: Self, max: Self) -> Self
where Self:Sized,

Restrict a value to a certain interval.Read more
1.8.0 ·Source§

implPartialEq forSystemTime

Source§

fneq(&self, other: &SystemTime) ->bool

Tests forself andother values to be equal, and is used by==.
1.0.0 ·Source§

fnne(&self, other:&Rhs) ->bool

Tests for!=. The default implementation is almost always sufficient,and should not be overridden without very good reason.
1.8.0 ·Source§

implPartialOrd forSystemTime

Source§

fnpartial_cmp(&self, other: &SystemTime) ->Option<Ordering>

This method returns an ordering betweenself andother values if one exists.Read more
1.0.0 ·Source§

fnlt(&self, other:&Rhs) ->bool

Tests less than (forself andother) and is used by the< operator.Read more
1.0.0 ·Source§

fnle(&self, other:&Rhs) ->bool

Tests less than or equal to (forself andother) and is used by the<= operator.Read more
1.0.0 ·Source§

fngt(&self, other:&Rhs) ->bool

Tests greater than (forself andother) and is used by the>operator.Read more
1.0.0 ·Source§

fnge(&self, other:&Rhs) ->bool

Tests greater than or equal to (forself andother) and is used bythe>= operator.Read more
1.8.0 ·Source§

implSub<Duration> forSystemTime

Source§

typeOutput =SystemTime

The resulting type after applying the- operator.
Source§

fnsub(self, dur:Duration) ->SystemTime

Performs the- operation.Read more
1.9.0 ·Source§

implSubAssign<Duration> forSystemTime

Source§

fnsub_assign(&mut self, other:Duration)

Performs the-= operation.Read more
1.8.0 ·Source§

implCopy forSystemTime

1.8.0 ·Source§

implEq forSystemTime

1.8.0 ·Source§

implStructuralPartialEq forSystemTime

Auto Trait Implementations§

§

implFreeze forSystemTime

§

implRefUnwindSafe forSystemTime

§

implSend forSystemTime

§

implSync forSystemTime

§

implUnpin forSystemTime

§

implUnwindSafe forSystemTime

Blanket Implementations§

Source§

impl<T>Any for T
where T: 'static + ?Sized,

Source§

fntype_id(&self) ->TypeId

Gets theTypeId ofself.Read more
Source§

impl<T>Borrow<T> for T
where T: ?Sized,

Source§

fnborrow(&self) ->&T

Immutably borrows from an owned value.Read more
Source§

impl<T>BorrowMut<T> for T
where T: ?Sized,

Source§

fnborrow_mut(&mut self) ->&mut T

Mutably borrows from an owned value.Read more
Source§

impl<T>CloneToUninit for T
where T:Clone,

Source§

unsafe fnclone_to_uninit(&self, dest:*mutu8)

🔬This is a nightly-only experimental API. (clone_to_uninit #126799)
Performs copy-assignment fromself todest.Read more
Source§

impl<T>From<T> for T

Source§

fnfrom(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U>Into<U> for T
where U:From<T>,

Source§

fninto(self) -> U

CallsU::from(self).

That is, this conversion is whatever the implementation ofFrom<T> for U chooses to do.

Source§

impl<T>ToOwned for T
where T:Clone,

Source§

typeOwned = T

The resulting type after obtaining ownership.
Source§

fnto_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning.Read more
Source§

fnclone_into(&self, target:&mut T)

Uses borrowed data to replace owned data, usually by cloning.Read more
Source§

impl<T, U>TryFrom<U> for T
where U:Into<T>,

Source§

typeError =Infallible

The type returned in the event of a conversion error.
Source§

fntry_from(value: U) ->Result<T, <T asTryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U>TryInto<U> for T
where U:TryFrom<T>,

Source§

typeError = <U asTryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fntry_into(self) ->Result<U, <U asTryFrom<T>>::Error>

Performs the conversion.

[8]ページ先頭

©2009-2025 Movatter.jp