std/
time.rs

1//! Temporal quantification.
2//!
3//! # Examples
4//!
5//! There are multiple ways to create a new [`Duration`]:
6//!
7//! ```
8//! # use std::time::Duration;
9//! let five_seconds = Duration::from_secs(5);
10//! assert_eq!(five_seconds, Duration::from_millis(5_000));
11//! assert_eq!(five_seconds, Duration::from_micros(5_000_000));
12//! assert_eq!(five_seconds, Duration::from_nanos(5_000_000_000));
13//!
14//! let ten_seconds = Duration::from_secs(10);
15//! let seven_nanos = Duration::from_nanos(7);
16//! let total = ten_seconds + seven_nanos;
17//! assert_eq!(total, Duration::new(10, 7));
18//! ```
19//!
20//! Using [`Instant`] to calculate how long a function took to run:
21//!
22//! ```ignore (incomplete)
23//! let now = Instant::now();
24//!
25//! // Calling a slow function, it may take a while
26//! slow_function();
27//!
28//! let elapsed_time = now.elapsed();
29//! println!("Running slow_function() took {} seconds.", elapsed_time.as_secs());
30//! ```
31
32#![stable(feature = "time", since = "1.3.0")]
33
34#[stable(feature = "time", since = "1.3.0")]
35pub use core::time::Duration;
36#[stable(feature = "duration_checked_float", since = "1.66.0")]
37pub use core::time::TryFromFloatSecsError;
38
39use crate::error::Error;
40use crate::fmt;
41use crate::ops::{Add, AddAssign, Sub, SubAssign};
42use crate::sys::time;
43use crate::sys_common::{FromInner, IntoInner};
44
45/// A measurement of a monotonically nondecreasing clock.
46/// Opaque and useful only with [`Duration`].
47///
48/// Instants are always guaranteed, barring [platform bugs], to be no less than any previously
49/// measured instant when created, and are often useful for tasks such as measuring
50/// benchmarks or timing how long an operation takes.
51///
52/// Note, however, that instants are **not** guaranteed to be **steady**. In other
53/// words, each tick of the underlying clock might not be the same length (e.g.
54/// some seconds may be longer than others). An instant may jump forwards or
55/// experience time dilation (slow down or speed up), but it will never go
56/// backwards.
57/// As part of this non-guarantee it is also not specified whether system suspends count as
58/// elapsed time or not. The behavior varies across platforms and Rust versions.
59///
60/// Instants are opaque types that can only be compared to one another. There is
61/// no method to get "the number of seconds" from an instant. Instead, it only
62/// allows measuring the duration between two instants (or comparing two
63/// instants).
64///
65/// The size of an `Instant` struct may vary depending on the target operating
66/// system.
67///
68/// Example:
69///
70/// ```no_run
71/// use std::time::{Duration, Instant};
72/// use std::thread::sleep;
73///
74/// fn main() {
75///    let now = Instant::now();
76///
77///    // we sleep for 2 seconds
78///    sleep(Duration::new(2, 0));
79///    // it prints '2'
80///    println!("{}", now.elapsed().as_secs());
81/// }
82/// ```
83///
84/// [platform bugs]: Instant#monotonicity
85///
86/// # OS-specific behaviors
87///
88/// An `Instant` is a wrapper around system-specific types and it may behave
89/// differently depending on the underlying operating system. For example,
90/// the following snippet is fine on Linux but panics on macOS:
91///
92/// ```no_run
93/// use std::time::{Instant, Duration};
94///
95/// let now = Instant::now();
96/// let days_per_10_millennia = 365_2425;
97/// let solar_seconds_per_day = 60 * 60 * 24;
98/// let millennium_in_solar_seconds = 31_556_952_000;
99/// assert_eq!(millennium_in_solar_seconds, days_per_10_millennia * solar_seconds_per_day / 10);
100///
101/// let duration = Duration::new(millennium_in_solar_seconds, 0);
102/// println!("{:?}", now + duration);
103/// ```
104///
105/// For cross-platform code, you can comfortably use durations of up to around one hundred years.
106///
107/// # Underlying System calls
108///
109/// The following system calls are [currently] being used by `now()` to find out
110/// the current time:
111///
112/// |  Platform |               System call                                            |
113/// |-----------|----------------------------------------------------------------------|
114/// | SGX       | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
115/// | UNIX      | [clock_gettime] with `CLOCK_MONOTONIC`                               |
116/// | Darwin    | [clock_gettime] with `CLOCK_UPTIME_RAW`                              |
117/// | VXWorks   | [clock_gettime] with `CLOCK_MONOTONIC`                               |
118/// | SOLID     | `get_tim`                                                            |
119/// | WASI      | [__wasi_clock_time_get] with `monotonic`                             |
120/// | Windows   | [QueryPerformanceCounter]                                            |
121///
122/// [currently]: crate::io#platform-specific-behavior
123/// [QueryPerformanceCounter]: https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter
124/// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
125/// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
126/// [__wasi_clock_time_get]: https://github.com/WebAssembly/WASI/blob/main/legacy/preview1/docs.md#clock_time_get
127/// [clock_gettime]: https://linux.die.net/man/3/clock_gettime
128///
129/// **Disclaimer:** These system calls might change over time.
130///
131/// > Note: mathematical operations like [`add`] may panic if the underlying
132/// > structure cannot represent the new point in time.
133///
134/// [`add`]: Instant::add
135///
136/// ## Monotonicity
137///
138/// On all platforms `Instant` will try to use an OS API that guarantees monotonic behavior
139/// if available, which is the case for all [tier 1] platforms.
140/// In practice such guarantees are – under rare circumstances – broken by hardware, virtualization
141/// or operating system bugs. To work around these bugs and platforms not offering monotonic clocks
142/// [`duration_since`], [`elapsed`] and [`sub`] saturate to zero. In older Rust versions this
143/// lead to a panic instead. [`checked_duration_since`] can be used to detect and handle situations
144/// where monotonicity is violated, or `Instant`s are subtracted in the wrong order.
145///
146/// This workaround obscures programming errors where earlier and later instants are accidentally
147/// swapped. For this reason future Rust versions may reintroduce panics.
148///
149/// [tier 1]: https://doc.rust-lang.org/rustc/platform-support.html
150/// [`duration_since`]: Instant::duration_since
151/// [`elapsed`]: Instant::elapsed
152/// [`sub`]: Instant::sub
153/// [`checked_duration_since`]: Instant::checked_duration_since
154///
155#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
156#[stable(feature = "time2", since = "1.8.0")]
157#[cfg_attr(not(test), rustc_diagnostic_item = "Instant")]
158pub struct Instant(time::Instant);
159
160/// A measurement of the system clock, useful for talking to
161/// external entities like the file system or other processes.
162///
163/// Distinct from the [`Instant`] type, this time measurement **is not
164/// monotonic**. This means that you can save a file to the file system, then
165/// save another file to the file system, **and the second file has a
166/// `SystemTime` measurement earlier than the first**. In other words, an
167/// operation that happens after another operation in real time may have an
168/// earlier `SystemTime`!
169///
170/// Consequently, comparing two `SystemTime` instances to learn about the
171/// duration between them returns a [`Result`] instead of an infallible [`Duration`]
172/// to indicate that this sort of time drift may happen and needs to be handled.
173///
174/// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
175/// constant is provided in this module as an anchor in time to learn
176/// information about a `SystemTime`. By calculating the duration from this
177/// fixed point in time, a `SystemTime` can be converted to a human-readable time,
178/// or perhaps some other string representation.
179///
180/// The size of a `SystemTime` struct may vary depending on the target operating
181/// system.
182///
183/// A `SystemTime` does not count leap seconds.
184/// `SystemTime::now()`'s behavior around a leap second
185/// is the same as the operating system's wall clock.
186/// The precise behavior near a leap second
187/// (e.g. whether the clock appears to run slow or fast, or stop, or jump)
188/// depends on platform and configuration,
189/// so should not be relied on.
190///
191/// Example:
192///
193/// ```no_run
194/// use std::time::{Duration, SystemTime};
195/// use std::thread::sleep;
196///
197/// fn main() {
198///    let now = SystemTime::now();
199///
200///    // we sleep for 2 seconds
201///    sleep(Duration::new(2, 0));
202///    match now.elapsed() {
203///        Ok(elapsed) => {
204///            // it prints '2'
205///            println!("{}", elapsed.as_secs());
206///        }
207///        Err(e) => {
208///            // the system clock went backwards!
209///            println!("Great Scott! {e:?}");
210///        }
211///    }
212/// }
213/// ```
214///
215/// # Platform-specific behavior
216///
217/// The precision of `SystemTime` can depend on the underlying OS-specific time format.
218/// For example, on Windows the time is represented in 100 nanosecond intervals whereas Linux
219/// can represent nanosecond intervals.
220///
221/// The following system calls are [currently] being used by `now()` to find out
222/// the current time:
223///
224/// |  Platform |               System call                                            |
225/// |-----------|----------------------------------------------------------------------|
226/// | SGX       | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
227/// | UNIX      | [clock_gettime (Realtime Clock)]                                     |
228/// | Darwin    | [clock_gettime (Realtime Clock)]                                     |
229/// | VXWorks   | [clock_gettime (Realtime Clock)]                                     |
230/// | SOLID     | `SOLID_RTC_ReadTime`                                                 |
231/// | WASI      | [__wasi_clock_time_get (Realtime Clock)]                             |
232/// | Windows   | [GetSystemTimePreciseAsFileTime] / [GetSystemTimeAsFileTime]         |
233///
234/// [currently]: crate::io#platform-specific-behavior
235/// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
236/// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
237/// [clock_gettime (Realtime Clock)]: https://linux.die.net/man/3/clock_gettime
238/// [__wasi_clock_time_get (Realtime Clock)]: https://github.com/WebAssembly/WASI/blob/main/legacy/preview1/docs.md#clock_time_get
239/// [GetSystemTimePreciseAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime
240/// [GetSystemTimeAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime
241///
242/// **Disclaimer:** These system calls might change over time.
243///
244/// > Note: mathematical operations like [`add`] may panic if the underlying
245/// > structure cannot represent the new point in time.
246///
247/// [`add`]: SystemTime::add
248/// [`UNIX_EPOCH`]: SystemTime::UNIX_EPOCH
249#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
250#[stable(feature = "time2", since = "1.8.0")]
251pub struct SystemTime(time::SystemTime);
252
253/// An error returned from the `duration_since` and `elapsed` methods on
254/// `SystemTime`, used to learn how far in the opposite direction a system time
255/// lies.
256///
257/// # Examples
258///
259/// ```no_run
260/// use std::thread::sleep;
261/// use std::time::{Duration, SystemTime};
262///
263/// let sys_time = SystemTime::now();
264/// sleep(Duration::from_secs(1));
265/// let new_sys_time = SystemTime::now();
266/// match sys_time.duration_since(new_sys_time) {
267///     Ok(_) => {}
268///     Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
269/// }
270/// ```
271#[derive(Clone, Debug)]
272#[stable(feature = "time2", since = "1.8.0")]
273pub struct SystemTimeError(Duration);
274
275impl Instant {
276    /// Returns an instant corresponding to "now".
277    ///
278    /// # Examples
279    ///
280    /// ```
281    /// use std::time::Instant;
282    ///
283    /// let now = Instant::now();
284    /// ```
285    #[must_use]
286    #[stable(feature = "time2", since = "1.8.0")]
287    #[cfg_attr(not(test), rustc_diagnostic_item = "instant_now")]
288    pub fn now() -> Instant {
289        Instant(time::Instant::now())
290    }
291
292    /// Returns the amount of time elapsed from another instant to this one,
293    /// or zero duration if that instant is later than this one.
294    ///
295    /// # Panics
296    ///
297    /// Previous Rust versions panicked when `earlier` was later than `self`. Currently this
298    /// method saturates. Future versions may reintroduce the panic in some circumstances.
299    /// See [Monotonicity].
300    ///
301    /// [Monotonicity]: Instant#monotonicity
302    ///
303    /// # Examples
304    ///
305    /// ```no_run
306    /// use std::time::{Duration, Instant};
307    /// use std::thread::sleep;
308    ///
309    /// let now = Instant::now();
310    /// sleep(Duration::new(1, 0));
311    /// let new_now = Instant::now();
312    /// println!("{:?}", new_now.duration_since(now));
313    /// println!("{:?}", now.duration_since(new_now)); // 0ns
314    /// ```
315    #[must_use]
316    #[stable(feature = "time2", since = "1.8.0")]
317    pub fn duration_since(&self, earlier: Instant) -> Duration {
318        self.checked_duration_since(earlier).unwrap_or_default()
319    }
320
321    /// Returns the amount of time elapsed from another instant to this one,
322    /// or None if that instant is later than this one.
323    ///
324    /// Due to [monotonicity bugs], even under correct logical ordering of the passed `Instant`s,
325    /// this method can return `None`.
326    ///
327    /// [monotonicity bugs]: Instant#monotonicity
328    ///
329    /// # Examples
330    ///
331    /// ```no_run
332    /// use std::time::{Duration, Instant};
333    /// use std::thread::sleep;
334    ///
335    /// let now = Instant::now();
336    /// sleep(Duration::new(1, 0));
337    /// let new_now = Instant::now();
338    /// println!("{:?}", new_now.checked_duration_since(now));
339    /// println!("{:?}", now.checked_duration_since(new_now)); // None
340    /// ```
341    #[must_use]
342    #[stable(feature = "checked_duration_since", since = "1.39.0")]
343    pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
344        self.0.checked_sub_instant(&earlier.0)
345    }
346
347    /// Returns the amount of time elapsed from another instant to this one,
348    /// or zero duration if that instant is later than this one.
349    ///
350    /// # Examples
351    ///
352    /// ```no_run
353    /// use std::time::{Duration, Instant};
354    /// use std::thread::sleep;
355    ///
356    /// let now = Instant::now();
357    /// sleep(Duration::new(1, 0));
358    /// let new_now = Instant::now();
359    /// println!("{:?}", new_now.saturating_duration_since(now));
360    /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
361    /// ```
362    #[must_use]
363    #[stable(feature = "checked_duration_since", since = "1.39.0")]
364    pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
365        self.checked_duration_since(earlier).unwrap_or_default()
366    }
367
368    /// Returns the amount of time elapsed since this instant.
369    ///
370    /// # Panics
371    ///
372    /// Previous Rust versions panicked when the current time was earlier than self. Currently this
373    /// method returns a Duration of zero in that case. Future versions may reintroduce the panic.
374    /// See [Monotonicity].
375    ///
376    /// [Monotonicity]: Instant#monotonicity
377    ///
378    /// # Examples
379    ///
380    /// ```no_run
381    /// use std::thread::sleep;
382    /// use std::time::{Duration, Instant};
383    ///
384    /// let instant = Instant::now();
385    /// let three_secs = Duration::from_secs(3);
386    /// sleep(three_secs);
387    /// assert!(instant.elapsed() >= three_secs);
388    /// ```
389    #[must_use]
390    #[stable(feature = "time2", since = "1.8.0")]
391    pub fn elapsed(&self) -> Duration {
392        Instant::now() - *self
393    }
394
395    /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
396    /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
397    /// otherwise.
398    #[stable(feature = "time_checked_add", since = "1.34.0")]
399    pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
400        self.0.checked_add_duration(&duration).map(Instant)
401    }
402
403    /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
404    /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
405    /// otherwise.
406    #[stable(feature = "time_checked_add", since = "1.34.0")]
407    pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
408        self.0.checked_sub_duration(&duration).map(Instant)
409    }
410
411    // Used by platform specific `sleep_until` implementations such as the one used on Linux.
412    #[cfg_attr(
413        not(target_os = "linux"),
414        allow(unused, reason = "not every platform has a specific `sleep_until`")
415    )]
416    pub(crate) fn into_inner(self) -> time::Instant {
417        self.0
418    }
419}
420
421#[stable(feature = "time2", since = "1.8.0")]
422impl Add<Duration> for Instant {
423    type Output = Instant;
424
425    /// # Panics
426    ///
427    /// This function may panic if the resulting point in time cannot be represented by the
428    /// underlying data structure. See [`Instant::checked_add`] for a version without panic.
429    fn add(self, other: Duration) -> Instant {
430        self.checked_add(other).expect("overflow when adding duration to instant")
431    }
432}
433
434#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
435impl AddAssign<Duration> for Instant {
436    fn add_assign(&mut self, other: Duration) {
437        *self = *self + other;
438    }
439}
440
441#[stable(feature = "time2", since = "1.8.0")]
442impl Sub<Duration> for Instant {
443    type Output = Instant;
444
445    fn sub(self, other: Duration) -> Instant {
446        self.checked_sub(other).expect("overflow when subtracting duration from instant")
447    }
448}
449
450#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
451impl SubAssign<Duration> for Instant {
452    fn sub_assign(&mut self, other: Duration) {
453        *self = *self - other;
454    }
455}
456
457#[stable(feature = "time2", since = "1.8.0")]
458impl Sub<Instant> for Instant {
459    type Output = Duration;
460
461    /// Returns the amount of time elapsed from another instant to this one,
462    /// or zero duration if that instant is later than this one.
463    ///
464    /// # Panics
465    ///
466    /// Previous Rust versions panicked when `other` was later than `self`. Currently this
467    /// method saturates. Future versions may reintroduce the panic in some circumstances.
468    /// See [Monotonicity].
469    ///
470    /// [Monotonicity]: Instant#monotonicity
471    fn sub(self, other: Instant) -> Duration {
472        self.duration_since(other)
473    }
474}
475
476#[stable(feature = "time2", since = "1.8.0")]
477impl fmt::Debug for Instant {
478    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
479        self.0.fmt(f)
480    }
481}
482
483impl SystemTime {
484    /// An anchor in time which can be used to create new `SystemTime` instances or
485    /// learn about where in time a `SystemTime` lies.
486    //
487    // NOTE! this documentation is duplicated, here and in std::time::UNIX_EPOCH.
488    // The two copies are not quite identical, because of the difference in naming.
489    ///
490    /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
491    /// respect to the system clock. Using `duration_since` on an existing
492    /// `SystemTime` instance can tell how far away from this point in time a
493    /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
494    /// `SystemTime` instance to represent another fixed point in time.
495    ///
496    /// `duration_since(UNIX_EPOCH).unwrap().as_secs()` returns
497    /// the number of non-leap seconds since the start of 1970 UTC.
498    /// This is a POSIX `time_t` (as a `u64`),
499    /// and is the same time representation as used in many Internet protocols.
500    ///
501    /// # Examples
502    ///
503    /// ```no_run
504    /// use std::time::SystemTime;
505    ///
506    /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
507    ///     Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
508    ///     Err(_) => panic!("SystemTime before UNIX EPOCH!"),
509    /// }
510    /// ```
511    #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
512    pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
513
514    /// Represents the maximum value representable by [`SystemTime`] on this platform.
515    ///
516    /// This value differs a lot between platforms, but it is always the case
517    /// that any positive addition of a [`Duration`], whose value is greater
518    /// than or equal to the time precision of the operating system, to
519    /// [`SystemTime::MAX`] will fail.
520    ///
521    /// # Examples
522    ///
523    /// ```no_run
524    /// #![feature(time_systemtime_limits)]
525    /// use std::time::{Duration, SystemTime};
526    ///
527    /// // Adding zero will change nothing.
528    /// assert_eq!(SystemTime::MAX.checked_add(Duration::ZERO), Some(SystemTime::MAX));
529    ///
530    /// // But adding just one second will already fail ...
531    /// //
532    /// // Keep in mind that this in fact may succeed, if the Duration is
533    /// // smaller than the time precision of the operating system, which
534    /// // happens to be 1ns on most operating systems, with Windows being the
535    /// // notable exception by using 100ns, hence why this example uses 1s.
536    /// assert_eq!(SystemTime::MAX.checked_add(Duration::new(1, 0)), None);
537    ///
538    /// // Utilize this for saturating arithmetic to improve error handling.
539    /// // In this case, we will use a certificate with a timestamp in the
540    /// // future as a practical example.
541    /// let configured_offset = Duration::from_secs(60 * 60 * 24);
542    /// let valid_after =
543    ///     SystemTime::now()
544    ///         .checked_add(configured_offset)
545    ///         .unwrap_or(SystemTime::MAX);
546    /// ```
547    #[unstable(feature = "time_systemtime_limits", issue = "149067")]
548    pub const MAX: SystemTime = SystemTime(time::SystemTime::MAX);
549
550    /// Represents the minimum value representable by [`SystemTime`] on this platform.
551    ///
552    /// This value differs a lot between platforms, but it is always the case
553    /// that any positive subtraction of a [`Duration`] from, whose value is
554    /// greater than or equal to the time precision of the operating system, to
555    /// [`SystemTime::MIN`] will fail.
556    ///
557    /// Depending on the platform, this may be either less than or equal to
558    /// [`SystemTime::UNIX_EPOCH`], depending on whether the operating system
559    /// supports the representation of timestamps before the Unix epoch or not.
560    /// However, it is always guaranteed that a [`SystemTime::UNIX_EPOCH`] fits
561    /// between a [`SystemTime::MIN`] and [`SystemTime::MAX`].
562    ///
563    /// # Examples
564    ///
565    /// ```
566    /// #![feature(time_systemtime_limits)]
567    /// use std::time::{Duration, SystemTime};
568    ///
569    /// // Subtracting zero will change nothing.
570    /// assert_eq!(SystemTime::MIN.checked_sub(Duration::ZERO), Some(SystemTime::MIN));
571    ///
572    /// // But subtracting just one second will already fail.
573    /// //
574    /// // Keep in mind that this in fact may succeed, if the Duration is
575    /// // smaller than the time precision of the operating system, which
576    /// // happens to be 1ns on most operating systems, with Windows being the
577    /// // notable exception by using 100ns, hence why this example uses 1s.
578    /// assert_eq!(SystemTime::MIN.checked_sub(Duration::new(1, 0)), None);
579    ///
580    /// // Utilize this for saturating arithmetic to improve error handling.
581    /// // In this case, we will use a cache expiry as a practical example.
582    /// let configured_expiry = Duration::from_secs(60 * 3);
583    /// let expiry_threshold =
584    ///     SystemTime::now()
585    ///         .checked_sub(configured_expiry)
586    ///         .unwrap_or(SystemTime::MIN);
587    /// ```
588    #[unstable(feature = "time_systemtime_limits", issue = "149067")]
589    pub const MIN: SystemTime = SystemTime(time::SystemTime::MIN);
590
591    /// Returns the system time corresponding to "now".
592    ///
593    /// # Examples
594    ///
595    /// ```
596    /// use std::time::SystemTime;
597    ///
598    /// let sys_time = SystemTime::now();
599    /// ```
600    #[must_use]
601    #[stable(feature = "time2", since = "1.8.0")]
602    pub fn now() -> SystemTime {
603        SystemTime(time::SystemTime::now())
604    }
605
606    /// Returns the amount of time elapsed from an earlier point in time.
607    ///
608    /// This function may fail because measurements taken earlier are not
609    /// guaranteed to always be before later measurements (due to anomalies such
610    /// as the system clock being adjusted either forwards or backwards).
611    /// [`Instant`] can be used to measure elapsed time without this risk of failure.
612    ///
613    /// If successful, <code>[Ok]\([Duration])</code> is returned where the duration represents
614    /// the amount of time elapsed from the specified measurement to this one.
615    ///
616    /// Returns an [`Err`] if `earlier` is later than `self`, and the error
617    /// contains how far from `self` the time is.
618    ///
619    /// # Examples
620    ///
621    /// ```no_run
622    /// use std::time::SystemTime;
623    ///
624    /// let sys_time = SystemTime::now();
625    /// let new_sys_time = SystemTime::now();
626    /// let difference = new_sys_time.duration_since(sys_time)
627    ///     .expect("Clock may have gone backwards");
628    /// println!("{difference:?}");
629    /// ```
630    #[stable(feature = "time2", since = "1.8.0")]
631    pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError> {
632        self.0.sub_time(&earlier.0).map_err(SystemTimeError)
633    }
634
635    /// Returns the difference from this system time to the
636    /// current clock time.
637    ///
638    /// This function may fail as the underlying system clock is susceptible to
639    /// drift and updates (e.g., the system clock could go backwards), so this
640    /// function might not always succeed. If successful, <code>[Ok]\([Duration])</code> is
641    /// returned where the duration represents the amount of time elapsed from
642    /// this time measurement to the current time.
643    ///
644    /// To measure elapsed time reliably, use [`Instant`] instead.
645    ///
646    /// Returns an [`Err`] if `self` is later than the current system time, and
647    /// the error contains how far from the current system time `self` is.
648    ///
649    /// # Examples
650    ///
651    /// ```no_run
652    /// use std::thread::sleep;
653    /// use std::time::{Duration, SystemTime};
654    ///
655    /// let sys_time = SystemTime::now();
656    /// let one_sec = Duration::from_secs(1);
657    /// sleep(one_sec);
658    /// assert!(sys_time.elapsed().unwrap() >= one_sec);
659    /// ```
660    #[stable(feature = "time2", since = "1.8.0")]
661    pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
662        SystemTime::now().duration_since(*self)
663    }
664
665    /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
666    /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
667    /// otherwise.
668    ///
669    /// In the case that the `duration` is smaller than the time precision of the operating
670    /// system, `Some(self)` will be returned.
671    #[stable(feature = "time_checked_add", since = "1.34.0")]
672    pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
673        self.0.checked_add_duration(&duration).map(SystemTime)
674    }
675
676    /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
677    /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
678    /// otherwise.
679    ///
680    /// In the case that the `duration` is smaller than the time precision of the operating
681    /// system, `Some(self)` will be returned.
682    #[stable(feature = "time_checked_add", since = "1.34.0")]
683    pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> {
684        self.0.checked_sub_duration(&duration).map(SystemTime)
685    }
686}
687
688#[stable(feature = "time2", since = "1.8.0")]
689impl Add<Duration> for SystemTime {
690    type Output = SystemTime;
691
692    /// # Panics
693    ///
694    /// This function may panic if the resulting point in time cannot be represented by the
695    /// underlying data structure. See [`SystemTime::checked_add`] for a version without panic.
696    fn add(self, dur: Duration) -> SystemTime {
697        self.checked_add(dur).expect("overflow when adding duration to instant")
698    }
699}
700
701#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
702impl AddAssign<Duration> for SystemTime {
703    fn add_assign(&mut self, other: Duration) {
704        *self = *self + other;
705    }
706}
707
708#[stable(feature = "time2", since = "1.8.0")]
709impl Sub<Duration> for SystemTime {
710    type Output = SystemTime;
711
712    fn sub(self, dur: Duration) -> SystemTime {
713        self.checked_sub(dur).expect("overflow when subtracting duration from instant")
714    }
715}
716
717#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
718impl SubAssign<Duration> for SystemTime {
719    fn sub_assign(&mut self, other: Duration) {
720        *self = *self - other;
721    }
722}
723
724#[stable(feature = "time2", since = "1.8.0")]
725impl fmt::Debug for SystemTime {
726    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
727        self.0.fmt(f)
728    }
729}
730
731/// An anchor in time which can be used to create new `SystemTime` instances or
732/// learn about where in time a `SystemTime` lies.
733//
734// NOTE! this documentation is duplicated, here and in SystemTime::UNIX_EPOCH.
735// The two copies are not quite identical, because of the difference in naming.
736///
737/// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
738/// respect to the system clock. Using `duration_since` on an existing
739/// [`SystemTime`] instance can tell how far away from this point in time a
740/// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
741/// [`SystemTime`] instance to represent another fixed point in time.
742///
743/// `duration_since(UNIX_EPOCH).unwrap().as_secs()` returns
744/// the number of non-leap seconds since the start of 1970 UTC.
745/// This is a POSIX `time_t` (as a `u64`),
746/// and is the same time representation as used in many Internet protocols.
747///
748/// # Examples
749///
750/// ```no_run
751/// use std::time::{SystemTime, UNIX_EPOCH};
752///
753/// match SystemTime::now().duration_since(UNIX_EPOCH) {
754///     Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
755///     Err(_) => panic!("SystemTime before UNIX EPOCH!"),
756/// }
757/// ```
758#[stable(feature = "time2", since = "1.8.0")]
759pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
760
761impl SystemTimeError {
762    /// Returns the positive duration which represents how far forward the
763    /// second system time was from the first.
764    ///
765    /// A `SystemTimeError` is returned from the [`SystemTime::duration_since`]
766    /// and [`SystemTime::elapsed`] methods whenever the second system time
767    /// represents a point later in time than the `self` of the method call.
768    ///
769    /// # Examples
770    ///
771    /// ```no_run
772    /// use std::thread::sleep;
773    /// use std::time::{Duration, SystemTime};
774    ///
775    /// let sys_time = SystemTime::now();
776    /// sleep(Duration::from_secs(1));
777    /// let new_sys_time = SystemTime::now();
778    /// match sys_time.duration_since(new_sys_time) {
779    ///     Ok(_) => {}
780    ///     Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
781    /// }
782    /// ```
783    #[must_use]
784    #[stable(feature = "time2", since = "1.8.0")]
785    pub fn duration(&self) -> Duration {
786        self.0
787    }
788}
789
790#[stable(feature = "time2", since = "1.8.0")]
791impl Error for SystemTimeError {}
792
793#[stable(feature = "time2", since = "1.8.0")]
794impl fmt::Display for SystemTimeError {
795    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
796        write!(f, "second time provided was later than self")
797    }
798}
799
800impl FromInner<time::SystemTime> for SystemTime {
801    fn from_inner(time: time::SystemTime) -> SystemTime {
802        SystemTime(time)
803    }
804}
805
806impl IntoInner<time::SystemTime> for SystemTime {
807    fn into_inner(self) -> time::SystemTime {
808        self.0
809    }
810}