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 max_seconds = u64::MAX / 1_000_000_000;
97/// let duration = Duration::new(max_seconds, 0);
98/// println!("{:?}", now + duration);
99/// ```
100///
101/// # Underlying System calls
102///
103/// The following system calls are [currently] being used by `now()` to find out
104/// the current time:
105///
106/// | Platform | System call |
107/// |-----------|----------------------------------------------------------------------|
108/// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
109/// | UNIX | [clock_gettime (Monotonic Clock)] |
110/// | Darwin | [clock_gettime (Monotonic Clock)] |
111/// | VXWorks | [clock_gettime (Monotonic Clock)] |
112/// | SOLID | `get_tim` |
113/// | WASI | [__wasi_clock_time_get (Monotonic Clock)] |
114/// | Windows | [QueryPerformanceCounter] |
115///
116/// [currently]: crate::io#platform-specific-behavior
117/// [QueryPerformanceCounter]: https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter
118/// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
119/// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
120/// [__wasi_clock_time_get (Monotonic Clock)]: https://github.com/WebAssembly/WASI/blob/main/legacy/preview1/docs.md#clock_time_get
121/// [clock_gettime (Monotonic Clock)]: https://linux.die.net/man/3/clock_gettime
122///
123/// **Disclaimer:** These system calls might change over time.
124///
125/// > Note: mathematical operations like [`add`] may panic if the underlying
126/// > structure cannot represent the new point in time.
127///
128/// [`add`]: Instant::add
129///
130/// ## Monotonicity
131///
132/// On all platforms `Instant` will try to use an OS API that guarantees monotonic behavior
133/// if available, which is the case for all [tier 1] platforms.
134/// In practice such guarantees are – under rare circumstances – broken by hardware, virtualization
135/// or operating system bugs. To work around these bugs and platforms not offering monotonic clocks
136/// [`duration_since`], [`elapsed`] and [`sub`] saturate to zero. In older Rust versions this
137/// lead to a panic instead. [`checked_duration_since`] can be used to detect and handle situations
138/// where monotonicity is violated, or `Instant`s are subtracted in the wrong order.
139///
140/// This workaround obscures programming errors where earlier and later instants are accidentally
141/// swapped. For this reason future Rust versions may reintroduce panics.
142///
143/// [tier 1]: https://doc.rust-lang.org/rustc/platform-support.html
144/// [`duration_since`]: Instant::duration_since
145/// [`elapsed`]: Instant::elapsed
146/// [`sub`]: Instant::sub
147/// [`checked_duration_since`]: Instant::checked_duration_since
148///
149#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
150#[stable(feature = "time2", since = "1.8.0")]
151#[cfg_attr(not(test), rustc_diagnostic_item = "Instant")]
152pub struct Instant(time::Instant);
153
154/// A measurement of the system clock, useful for talking to
155/// external entities like the file system or other processes.
156///
157/// Distinct from the [`Instant`] type, this time measurement **is not
158/// monotonic**. This means that you can save a file to the file system, then
159/// save another file to the file system, **and the second file has a
160/// `SystemTime` measurement earlier than the first**. In other words, an
161/// operation that happens after another operation in real time may have an
162/// earlier `SystemTime`!
163///
164/// Consequently, comparing two `SystemTime` instances to learn about the
165/// duration between them returns a [`Result`] instead of an infallible [`Duration`]
166/// to indicate that this sort of time drift may happen and needs to be handled.
167///
168/// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
169/// constant is provided in this module as an anchor in time to learn
170/// information about a `SystemTime`. By calculating the duration from this
171/// fixed point in time, a `SystemTime` can be converted to a human-readable time,
172/// or perhaps some other string representation.
173///
174/// The size of a `SystemTime` struct may vary depending on the target operating
175/// system.
176///
177/// A `SystemTime` does not count leap seconds.
178/// `SystemTime::now()`'s behavior around a leap second
179/// is the same as the operating system's wall clock.
180/// The precise behavior near a leap second
181/// (e.g. whether the clock appears to run slow or fast, or stop, or jump)
182/// depends on platform and configuration,
183/// so should not be relied on.
184///
185/// Example:
186///
187/// ```no_run
188/// use std::time::{Duration, SystemTime};
189/// use std::thread::sleep;
190///
191/// fn main() {
192/// let now = SystemTime::now();
193///
194/// // we sleep for 2 seconds
195/// sleep(Duration::new(2, 0));
196/// match now.elapsed() {
197/// Ok(elapsed) => {
198/// // it prints '2'
199/// println!("{}", elapsed.as_secs());
200/// }
201/// Err(e) => {
202/// // an error occurred!
203/// println!("Error: {e:?}");
204/// }
205/// }
206/// }
207/// ```
208///
209/// # Platform-specific behavior
210///
211/// The precision of `SystemTime` can depend on the underlying OS-specific time format.
212/// For example, on Windows the time is represented in 100 nanosecond intervals whereas Linux
213/// can represent nanosecond intervals.
214///
215/// The following system calls are [currently] being used by `now()` to find out
216/// the current time:
217///
218/// | Platform | System call |
219/// |-----------|----------------------------------------------------------------------|
220/// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
221/// | UNIX | [clock_gettime (Realtime Clock)] |
222/// | Darwin | [clock_gettime (Realtime Clock)] |
223/// | VXWorks | [clock_gettime (Realtime Clock)] |
224/// | SOLID | `SOLID_RTC_ReadTime` |
225/// | WASI | [__wasi_clock_time_get (Realtime Clock)] |
226/// | Windows | [GetSystemTimePreciseAsFileTime] / [GetSystemTimeAsFileTime] |
227///
228/// [currently]: crate::io#platform-specific-behavior
229/// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
230/// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
231/// [clock_gettime (Realtime Clock)]: https://linux.die.net/man/3/clock_gettime
232/// [__wasi_clock_time_get (Realtime Clock)]: https://github.com/WebAssembly/WASI/blob/main/legacy/preview1/docs.md#clock_time_get
233/// [GetSystemTimePreciseAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime
234/// [GetSystemTimeAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime
235///
236/// **Disclaimer:** These system calls might change over time.
237///
238/// > Note: mathematical operations like [`add`] may panic if the underlying
239/// > structure cannot represent the new point in time.
240///
241/// [`add`]: SystemTime::add
242#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
243#[stable(feature = "time2", since = "1.8.0")]
244pub struct SystemTime(time::SystemTime);
245
246/// An error returned from the `duration_since` and `elapsed` methods on
247/// `SystemTime`, used to learn how far in the opposite direction a system time
248/// lies.
249///
250/// # Examples
251///
252/// ```no_run
253/// use std::thread::sleep;
254/// use std::time::{Duration, SystemTime};
255///
256/// let sys_time = SystemTime::now();
257/// sleep(Duration::from_secs(1));
258/// let new_sys_time = SystemTime::now();
259/// match sys_time.duration_since(new_sys_time) {
260/// Ok(_) => {}
261/// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
262/// }
263/// ```
264#[derive(Clone, Debug)]
265#[stable(feature = "time2", since = "1.8.0")]
266pub struct SystemTimeError(Duration);
267
268impl Instant {
269 /// Returns an instant corresponding to "now".
270 ///
271 /// # Examples
272 ///
273 /// ```
274 /// use std::time::Instant;
275 ///
276 /// let now = Instant::now();
277 /// ```
278 #[must_use]
279 #[stable(feature = "time2", since = "1.8.0")]
280 #[cfg_attr(not(test), rustc_diagnostic_item = "instant_now")]
281 pub fn now() -> Instant {
282 Instant(time::Instant::now())
283 }
284
285 /// Returns the amount of time elapsed from another instant to this one,
286 /// or zero duration if that instant is later than this one.
287 ///
288 /// # Panics
289 ///
290 /// Previous Rust versions panicked when `earlier` was later than `self`. Currently this
291 /// method saturates. Future versions may reintroduce the panic in some circumstances.
292 /// See [Monotonicity].
293 ///
294 /// [Monotonicity]: Instant#monotonicity
295 ///
296 /// # Examples
297 ///
298 /// ```no_run
299 /// use std::time::{Duration, Instant};
300 /// use std::thread::sleep;
301 ///
302 /// let now = Instant::now();
303 /// sleep(Duration::new(1, 0));
304 /// let new_now = Instant::now();
305 /// println!("{:?}", new_now.duration_since(now));
306 /// println!("{:?}", now.duration_since(new_now)); // 0ns
307 /// ```
308 #[must_use]
309 #[stable(feature = "time2", since = "1.8.0")]
310 pub fn duration_since(&self, earlier: Instant) -> Duration {
311 self.checked_duration_since(earlier).unwrap_or_default()
312 }
313
314 /// Returns the amount of time elapsed from another instant to this one,
315 /// or None if that instant is later than this one.
316 ///
317 /// Due to [monotonicity bugs], even under correct logical ordering of the passed `Instant`s,
318 /// this method can return `None`.
319 ///
320 /// [monotonicity bugs]: Instant#monotonicity
321 ///
322 /// # Examples
323 ///
324 /// ```no_run
325 /// use std::time::{Duration, Instant};
326 /// use std::thread::sleep;
327 ///
328 /// let now = Instant::now();
329 /// sleep(Duration::new(1, 0));
330 /// let new_now = Instant::now();
331 /// println!("{:?}", new_now.checked_duration_since(now));
332 /// println!("{:?}", now.checked_duration_since(new_now)); // None
333 /// ```
334 #[must_use]
335 #[stable(feature = "checked_duration_since", since = "1.39.0")]
336 pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
337 self.0.checked_sub_instant(&earlier.0)
338 }
339
340 /// Returns the amount of time elapsed from another instant to this one,
341 /// or zero duration if that instant is later than this one.
342 ///
343 /// # Examples
344 ///
345 /// ```no_run
346 /// use std::time::{Duration, Instant};
347 /// use std::thread::sleep;
348 ///
349 /// let now = Instant::now();
350 /// sleep(Duration::new(1, 0));
351 /// let new_now = Instant::now();
352 /// println!("{:?}", new_now.saturating_duration_since(now));
353 /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
354 /// ```
355 #[must_use]
356 #[stable(feature = "checked_duration_since", since = "1.39.0")]
357 pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
358 self.checked_duration_since(earlier).unwrap_or_default()
359 }
360
361 /// Returns the amount of time elapsed since this instant.
362 ///
363 /// # Panics
364 ///
365 /// Previous Rust versions panicked when the current time was earlier than self. Currently this
366 /// method returns a Duration of zero in that case. Future versions may reintroduce the panic.
367 /// See [Monotonicity].
368 ///
369 /// [Monotonicity]: Instant#monotonicity
370 ///
371 /// # Examples
372 ///
373 /// ```no_run
374 /// use std::thread::sleep;
375 /// use std::time::{Duration, Instant};
376 ///
377 /// let instant = Instant::now();
378 /// let three_secs = Duration::from_secs(3);
379 /// sleep(three_secs);
380 /// assert!(instant.elapsed() >= three_secs);
381 /// ```
382 #[must_use]
383 #[stable(feature = "time2", since = "1.8.0")]
384 pub fn elapsed(&self) -> Duration {
385 Instant::now() - *self
386 }
387
388 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
389 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
390 /// otherwise.
391 #[stable(feature = "time_checked_add", since = "1.34.0")]
392 pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
393 self.0.checked_add_duration(&duration).map(Instant)
394 }
395
396 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
397 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
398 /// otherwise.
399 #[stable(feature = "time_checked_add", since = "1.34.0")]
400 pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
401 self.0.checked_sub_duration(&duration).map(Instant)
402 }
403}
404
405#[stable(feature = "time2", since = "1.8.0")]
406impl Add<Duration> for Instant {
407 type Output = Instant;
408
409 /// # Panics
410 ///
411 /// This function may panic if the resulting point in time cannot be represented by the
412 /// underlying data structure. See [`Instant::checked_add`] for a version without panic.
413 fn add(self, other: Duration) -> Instant {
414 self.checked_add(other).expect("overflow when adding duration to instant")
415 }
416}
417
418#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
419impl AddAssign<Duration> for Instant {
420 fn add_assign(&mut self, other: Duration) {
421 *self = *self + other;
422 }
423}
424
425#[stable(feature = "time2", since = "1.8.0")]
426impl Sub<Duration> for Instant {
427 type Output = Instant;
428
429 fn sub(self, other: Duration) -> Instant {
430 self.checked_sub(other).expect("overflow when subtracting duration from instant")
431 }
432}
433
434#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
435impl SubAssign<Duration> for Instant {
436 fn sub_assign(&mut self, other: Duration) {
437 *self = *self - other;
438 }
439}
440
441#[stable(feature = "time2", since = "1.8.0")]
442impl Sub<Instant> for Instant {
443 type Output = Duration;
444
445 /// Returns the amount of time elapsed from another instant to this one,
446 /// or zero duration if that instant is later than this one.
447 ///
448 /// # Panics
449 ///
450 /// Previous Rust versions panicked when `other` was later than `self`. Currently this
451 /// method saturates. Future versions may reintroduce the panic in some circumstances.
452 /// See [Monotonicity].
453 ///
454 /// [Monotonicity]: Instant#monotonicity
455 fn sub(self, other: Instant) -> Duration {
456 self.duration_since(other)
457 }
458}
459
460#[stable(feature = "time2", since = "1.8.0")]
461impl fmt::Debug for Instant {
462 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
463 self.0.fmt(f)
464 }
465}
466
467impl SystemTime {
468 /// An anchor in time which can be used to create new `SystemTime` instances or
469 /// learn about where in time a `SystemTime` lies.
470 //
471 // NOTE! this documentation is duplicated, here and in std::time::UNIX_EPOCH.
472 // The two copies are not quite identical, because of the difference in naming.
473 ///
474 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
475 /// respect to the system clock. Using `duration_since` on an existing
476 /// `SystemTime` instance can tell how far away from this point in time a
477 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
478 /// `SystemTime` instance to represent another fixed point in time.
479 ///
480 /// `duration_since(UNIX_EPOCH).unwrap().as_secs()` returns
481 /// the number of non-leap seconds since the start of 1970 UTC.
482 /// This is a POSIX `time_t` (as a `u64`),
483 /// and is the same time representation as used in many Internet protocols.
484 ///
485 /// # Examples
486 ///
487 /// ```no_run
488 /// use std::time::SystemTime;
489 ///
490 /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
491 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
492 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
493 /// }
494 /// ```
495 #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
496 pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
497
498 /// Returns the system time corresponding to "now".
499 ///
500 /// # Examples
501 ///
502 /// ```
503 /// use std::time::SystemTime;
504 ///
505 /// let sys_time = SystemTime::now();
506 /// ```
507 #[must_use]
508 #[stable(feature = "time2", since = "1.8.0")]
509 pub fn now() -> SystemTime {
510 SystemTime(time::SystemTime::now())
511 }
512
513 /// Returns the amount of time elapsed from an earlier point in time.
514 ///
515 /// This function may fail because measurements taken earlier are not
516 /// guaranteed to always be before later measurements (due to anomalies such
517 /// as the system clock being adjusted either forwards or backwards).
518 /// [`Instant`] can be used to measure elapsed time without this risk of failure.
519 ///
520 /// If successful, <code>[Ok]\([Duration])</code> is returned where the duration represents
521 /// the amount of time elapsed from the specified measurement to this one.
522 ///
523 /// Returns an [`Err`] if `earlier` is later than `self`, and the error
524 /// contains how far from `self` the time is.
525 ///
526 /// # Examples
527 ///
528 /// ```no_run
529 /// use std::time::SystemTime;
530 ///
531 /// let sys_time = SystemTime::now();
532 /// let new_sys_time = SystemTime::now();
533 /// let difference = new_sys_time.duration_since(sys_time)
534 /// .expect("Clock may have gone backwards");
535 /// println!("{difference:?}");
536 /// ```
537 #[stable(feature = "time2", since = "1.8.0")]
538 pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError> {
539 self.0.sub_time(&earlier.0).map_err(SystemTimeError)
540 }
541
542 /// Returns the difference from this system time to the
543 /// current clock time.
544 ///
545 /// This function may fail as the underlying system clock is susceptible to
546 /// drift and updates (e.g., the system clock could go backwards), so this
547 /// function might not always succeed. If successful, <code>[Ok]\([Duration])</code> is
548 /// returned where the duration represents the amount of time elapsed from
549 /// this time measurement to the current time.
550 ///
551 /// To measure elapsed time reliably, use [`Instant`] instead.
552 ///
553 /// Returns an [`Err`] if `self` is later than the current system time, and
554 /// the error contains how far from the current system time `self` is.
555 ///
556 /// # Examples
557 ///
558 /// ```no_run
559 /// use std::thread::sleep;
560 /// use std::time::{Duration, SystemTime};
561 ///
562 /// let sys_time = SystemTime::now();
563 /// let one_sec = Duration::from_secs(1);
564 /// sleep(one_sec);
565 /// assert!(sys_time.elapsed().unwrap() >= one_sec);
566 /// ```
567 #[stable(feature = "time2", since = "1.8.0")]
568 pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
569 SystemTime::now().duration_since(*self)
570 }
571
572 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
573 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
574 /// otherwise.
575 #[stable(feature = "time_checked_add", since = "1.34.0")]
576 pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
577 self.0.checked_add_duration(&duration).map(SystemTime)
578 }
579
580 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
581 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
582 /// otherwise.
583 #[stable(feature = "time_checked_add", since = "1.34.0")]
584 pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> {
585 self.0.checked_sub_duration(&duration).map(SystemTime)
586 }
587}
588
589#[stable(feature = "time2", since = "1.8.0")]
590impl Add<Duration> for SystemTime {
591 type Output = SystemTime;
592
593 /// # Panics
594 ///
595 /// This function may panic if the resulting point in time cannot be represented by the
596 /// underlying data structure. See [`SystemTime::checked_add`] for a version without panic.
597 fn add(self, dur: Duration) -> SystemTime {
598 self.checked_add(dur).expect("overflow when adding duration to instant")
599 }
600}
601
602#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
603impl AddAssign<Duration> for SystemTime {
604 fn add_assign(&mut self, other: Duration) {
605 *self = *self + other;
606 }
607}
608
609#[stable(feature = "time2", since = "1.8.0")]
610impl Sub<Duration> for SystemTime {
611 type Output = SystemTime;
612
613 fn sub(self, dur: Duration) -> SystemTime {
614 self.checked_sub(dur).expect("overflow when subtracting duration from instant")
615 }
616}
617
618#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
619impl SubAssign<Duration> for SystemTime {
620 fn sub_assign(&mut self, other: Duration) {
621 *self = *self - other;
622 }
623}
624
625#[stable(feature = "time2", since = "1.8.0")]
626impl fmt::Debug for SystemTime {
627 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
628 self.0.fmt(f)
629 }
630}
631
632/// An anchor in time which can be used to create new `SystemTime` instances or
633/// learn about where in time a `SystemTime` lies.
634//
635// NOTE! this documentation is duplicated, here and in SystemTime::UNIX_EPOCH.
636// The two copies are not quite identical, because of the difference in naming.
637///
638/// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
639/// respect to the system clock. Using `duration_since` on an existing
640/// [`SystemTime`] instance can tell how far away from this point in time a
641/// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
642/// [`SystemTime`] instance to represent another fixed point in time.
643///
644/// `duration_since(UNIX_EPOCH).unwrap().as_secs()` returns
645/// the number of non-leap seconds since the start of 1970 UTC.
646/// This is a POSIX `time_t` (as a `u64`),
647/// and is the same time representation as used in many Internet protocols.
648///
649/// # Examples
650///
651/// ```no_run
652/// use std::time::{SystemTime, UNIX_EPOCH};
653///
654/// match SystemTime::now().duration_since(UNIX_EPOCH) {
655/// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
656/// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
657/// }
658/// ```
659#[stable(feature = "time2", since = "1.8.0")]
660pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
661
662impl SystemTimeError {
663 /// Returns the positive duration which represents how far forward the
664 /// second system time was from the first.
665 ///
666 /// A `SystemTimeError` is returned from the [`SystemTime::duration_since`]
667 /// and [`SystemTime::elapsed`] methods whenever the second system time
668 /// represents a point later in time than the `self` of the method call.
669 ///
670 /// # Examples
671 ///
672 /// ```no_run
673 /// use std::thread::sleep;
674 /// use std::time::{Duration, SystemTime};
675 ///
676 /// let sys_time = SystemTime::now();
677 /// sleep(Duration::from_secs(1));
678 /// let new_sys_time = SystemTime::now();
679 /// match sys_time.duration_since(new_sys_time) {
680 /// Ok(_) => {}
681 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
682 /// }
683 /// ```
684 #[must_use]
685 #[stable(feature = "time2", since = "1.8.0")]
686 pub fn duration(&self) -> Duration {
687 self.0
688 }
689}
690
691#[stable(feature = "time2", since = "1.8.0")]
692impl Error for SystemTimeError {
693 #[allow(deprecated)]
694 fn description(&self) -> &str {
695 "other time was not earlier than self"
696 }
697}
698
699#[stable(feature = "time2", since = "1.8.0")]
700impl fmt::Display for SystemTimeError {
701 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
702 write!(f, "second time provided was later than self")
703 }
704}
705
706impl FromInner<time::SystemTime> for SystemTime {
707 fn from_inner(time: time::SystemTime) -> SystemTime {
708 SystemTime(time)
709 }
710}
711
712impl IntoInner<time::SystemTime> for SystemTime {
713 fn into_inner(self) -> time::SystemTime {
714 self.0
715 }
716}