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 (Monotonic Clock)] |
116/// | Darwin | [clock_gettime (Monotonic Clock)] |
117/// | VXWorks | [clock_gettime (Monotonic Clock)] |
118/// | SOLID | `get_tim` |
119/// | WASI | [__wasi_clock_time_get (Monotonic Clock)] |
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 (Monotonic Clock)]: https://github.com/WebAssembly/WASI/blob/main/legacy/preview1/docs.md#clock_time_get
127/// [clock_gettime (Monotonic Clock)]: 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 /// Returns the system time corresponding to "now".
515 ///
516 /// # Examples
517 ///
518 /// ```
519 /// use std::time::SystemTime;
520 ///
521 /// let sys_time = SystemTime::now();
522 /// ```
523 #[must_use]
524 #[stable(feature = "time2", since = "1.8.0")]
525 pub fn now() -> SystemTime {
526 SystemTime(time::SystemTime::now())
527 }
528
529 /// Returns the amount of time elapsed from an earlier point in time.
530 ///
531 /// This function may fail because measurements taken earlier are not
532 /// guaranteed to always be before later measurements (due to anomalies such
533 /// as the system clock being adjusted either forwards or backwards).
534 /// [`Instant`] can be used to measure elapsed time without this risk of failure.
535 ///
536 /// If successful, <code>[Ok]\([Duration])</code> is returned where the duration represents
537 /// the amount of time elapsed from the specified measurement to this one.
538 ///
539 /// Returns an [`Err`] if `earlier` is later than `self`, and the error
540 /// contains how far from `self` the time is.
541 ///
542 /// # Examples
543 ///
544 /// ```no_run
545 /// use std::time::SystemTime;
546 ///
547 /// let sys_time = SystemTime::now();
548 /// let new_sys_time = SystemTime::now();
549 /// let difference = new_sys_time.duration_since(sys_time)
550 /// .expect("Clock may have gone backwards");
551 /// println!("{difference:?}");
552 /// ```
553 #[stable(feature = "time2", since = "1.8.0")]
554 #[rustc_const_unstable(feature = "const_system_time", issue = "144517")]
555 pub const fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError> {
556 // FIXME: map_err in const
557 match self.0.sub_time(&earlier.0) {
558 Ok(time) => Ok(time),
559 Err(err) => Err(SystemTimeError(err)),
560 }
561 }
562
563 /// Returns the difference from this system time to the
564 /// current clock time.
565 ///
566 /// This function may fail as the underlying system clock is susceptible to
567 /// drift and updates (e.g., the system clock could go backwards), so this
568 /// function might not always succeed. If successful, <code>[Ok]\([Duration])</code> is
569 /// returned where the duration represents the amount of time elapsed from
570 /// this time measurement to the current time.
571 ///
572 /// To measure elapsed time reliably, use [`Instant`] instead.
573 ///
574 /// Returns an [`Err`] if `self` is later than the current system time, and
575 /// the error contains how far from the current system time `self` is.
576 ///
577 /// # Examples
578 ///
579 /// ```no_run
580 /// use std::thread::sleep;
581 /// use std::time::{Duration, SystemTime};
582 ///
583 /// let sys_time = SystemTime::now();
584 /// let one_sec = Duration::from_secs(1);
585 /// sleep(one_sec);
586 /// assert!(sys_time.elapsed().unwrap() >= one_sec);
587 /// ```
588 #[stable(feature = "time2", since = "1.8.0")]
589 pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
590 SystemTime::now().duration_since(*self)
591 }
592
593 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
594 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
595 /// otherwise.
596 #[stable(feature = "time_checked_add", since = "1.34.0")]
597 #[rustc_const_unstable(feature = "const_system_time", issue = "144517")]
598 pub const fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
599 self.0.checked_add_duration(&duration).map(SystemTime)
600 }
601
602 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
603 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
604 /// otherwise.
605 #[stable(feature = "time_checked_add", since = "1.34.0")]
606 #[rustc_const_unstable(feature = "const_system_time", issue = "144517")]
607 pub const fn checked_sub(&self, duration: Duration) -> Option<SystemTime> {
608 self.0.checked_sub_duration(&duration).map(SystemTime)
609 }
610}
611
612#[stable(feature = "time2", since = "1.8.0")]
613#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
614impl const Add<Duration> for SystemTime {
615 type Output = SystemTime;
616
617 /// # Panics
618 ///
619 /// This function may panic if the resulting point in time cannot be represented by the
620 /// underlying data structure. See [`SystemTime::checked_add`] for a version without panic.
621 fn add(self, dur: Duration) -> SystemTime {
622 self.checked_add(dur).expect("overflow when adding duration to instant")
623 }
624}
625
626#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
627#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
628impl const AddAssign<Duration> for SystemTime {
629 fn add_assign(&mut self, other: Duration) {
630 *self = *self + other;
631 }
632}
633
634#[stable(feature = "time2", since = "1.8.0")]
635#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
636impl const Sub<Duration> for SystemTime {
637 type Output = SystemTime;
638
639 fn sub(self, dur: Duration) -> SystemTime {
640 self.checked_sub(dur).expect("overflow when subtracting duration from instant")
641 }
642}
643
644#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
645#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
646impl const SubAssign<Duration> for SystemTime {
647 fn sub_assign(&mut self, other: Duration) {
648 *self = *self - other;
649 }
650}
651
652#[stable(feature = "time2", since = "1.8.0")]
653impl fmt::Debug for SystemTime {
654 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
655 self.0.fmt(f)
656 }
657}
658
659/// An anchor in time which can be used to create new `SystemTime` instances or
660/// learn about where in time a `SystemTime` lies.
661//
662// NOTE! this documentation is duplicated, here and in SystemTime::UNIX_EPOCH.
663// The two copies are not quite identical, because of the difference in naming.
664///
665/// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
666/// respect to the system clock. Using `duration_since` on an existing
667/// [`SystemTime`] instance can tell how far away from this point in time a
668/// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
669/// [`SystemTime`] instance to represent another fixed point in time.
670///
671/// `duration_since(UNIX_EPOCH).unwrap().as_secs()` returns
672/// the number of non-leap seconds since the start of 1970 UTC.
673/// This is a POSIX `time_t` (as a `u64`),
674/// and is the same time representation as used in many Internet protocols.
675///
676/// # Examples
677///
678/// ```no_run
679/// use std::time::{SystemTime, UNIX_EPOCH};
680///
681/// match SystemTime::now().duration_since(UNIX_EPOCH) {
682/// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
683/// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
684/// }
685/// ```
686#[stable(feature = "time2", since = "1.8.0")]
687pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
688
689impl SystemTimeError {
690 /// Returns the positive duration which represents how far forward the
691 /// second system time was from the first.
692 ///
693 /// A `SystemTimeError` is returned from the [`SystemTime::duration_since`]
694 /// and [`SystemTime::elapsed`] methods whenever the second system time
695 /// represents a point later in time than the `self` of the method call.
696 ///
697 /// # Examples
698 ///
699 /// ```no_run
700 /// use std::thread::sleep;
701 /// use std::time::{Duration, SystemTime};
702 ///
703 /// let sys_time = SystemTime::now();
704 /// sleep(Duration::from_secs(1));
705 /// let new_sys_time = SystemTime::now();
706 /// match sys_time.duration_since(new_sys_time) {
707 /// Ok(_) => {}
708 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
709 /// }
710 /// ```
711 #[must_use]
712 #[stable(feature = "time2", since = "1.8.0")]
713 #[rustc_const_unstable(feature = "const_system_time", issue = "144517")]
714 pub const fn duration(&self) -> Duration {
715 self.0
716 }
717}
718
719#[stable(feature = "time2", since = "1.8.0")]
720impl Error for SystemTimeError {
721 #[allow(deprecated)]
722 fn description(&self) -> &str {
723 "other time was not earlier than self"
724 }
725}
726
727#[stable(feature = "time2", since = "1.8.0")]
728impl fmt::Display for SystemTimeError {
729 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
730 write!(f, "second time provided was later than self")
731 }
732}
733
734impl FromInner<time::SystemTime> for SystemTime {
735 fn from_inner(time: time::SystemTime) -> SystemTime {
736 SystemTime(time)
737 }
738}
739
740impl IntoInner<time::SystemTime> for SystemTime {
741 fn into_inner(self) -> time::SystemTime {
742 self.0
743 }
744}