Skip to main content

Timestamp

Struct Timestamp 

Source
pub struct Timestamp { /* private fields */ }
Expand description

A timestamp value that can be serialized to and deserialized from JSON.

Timestamp is stored internally as (seconds: i64, nanos: u32), where seconds counts (signed) seconds since the Unix epoch and nanos is always in [0, 1_000_000_000). This matches the google.protobuf.Timestamp convention and lets the type be no_std-compatible. Negative whole-second values combined with a positive nanos mean the same instant as the float seconds + nanos / 1e9, e.g. (-5, 200_000_000) is -4.8s.

§Invariants

Every Timestamp value satisfies:

  • seconds is in SECONDS_MIN..=SECONDS_MAX, i.e. it represents an instant between 0001-01-01T00:00:00Z and 9999-12-31T23:59:59Z inclusive.
  • nanos is in [0, 1_000_000_000).

All public constructors enforce these invariants — Timestamp::now, Timestamp::from_unix, Timestamp::from_str, From<SystemTime>, and the optional From<chrono::DateTime<Tz>> either validate, saturate, or are infallible by construction. As a result, Buffer::format and fmt::Display never fail.

With the default std feature, this type round-trips to and from std::time::SystemTime efficiently — the conversion is just a duration_since(UNIX_EPOCH) followed by storing the two fields (saturating at the supported range bounds).

§Creating timestamps

// From Unix seconds + nanoseconds.
let ts = Timestamp::from_unix(1_641_006_000, 0).unwrap();

// Equivalent via the `TryFrom<(i64, u32)>` impl.
let ts = Timestamp::try_from((1_641_006_000i64, 0u32)).unwrap();

// With the `std` feature: from current system time.
let now = Timestamp::now();
let ts = Timestamp::from(std::time::SystemTime::now());

§Inspecting timestamps

let ts = Timestamp::from_unix(1_641_006_000, 250_000_000).unwrap();
assert_eq!(ts.seconds(), 1_641_006_000);
assert_eq!(ts.subsec_nanos(), 250_000_000);

Implementations§

Source§

impl Timestamp

Source

pub fn from_unix(seconds: i64, nanos: u32) -> Result<Self, TimestampError>

Constructs a Timestamp from Unix seconds and nanoseconds.

Returns TimestampError::OutOfRange if seconds is outside the representable year 1..=9999 range, or if nanos >= 1_000_000_000.

§Examples
let ts = Timestamp::from_unix(0, 0).unwrap();
assert_eq!(ts.seconds(), 0);
assert_eq!(ts.subsec_nanos(), 0);
Source

pub fn seconds(&self) -> i64

Returns the (signed) seconds component, counted from the Unix epoch.

Source

pub fn subsec_nanos(&self) -> u32

Returns the fractional-second component, in nanoseconds.

The returned value is always in [0, 1_000_000_000). The naming matches std::time::Duration::subsec_nanos.

Source

pub fn now() -> Self

Returns a Timestamp representing the current system time.

This is a convenience method for Timestamp::from(SystemTime::now()).

Trait Implementations§

Source§

impl Clone for Timestamp

Source§

fn clone(&self) -> Timestamp

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Timestamp

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

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

impl<'de> Deserialize<'de> for Timestamp

Available on crate feature serde only.
Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Timestamp

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

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

impl From<&SystemTime> for Timestamp

Available on crate feature std only.

Wraps a SystemTime reference as a Timestamp. See From<SystemTime> for the saturation contract.

Source§

fn from(value: &SystemTime) -> Self

Converts to this type from the input type.
Source§

impl From<&Timestamp> for Timestamp

Source§

fn from(value: &Timestamp) -> Self

Converts to this type from the input type.
Source§

impl From<SystemTime> for Timestamp

Available on crate feature std only.

Converts a SystemTime into a Timestamp by computing its offset from the Unix epoch.

SystemTime can in principle represent instants outside the Timestamp range (year 1 through year 9999); such values are saturated to the nearest in-range second. In practice this only affects deliberately constructed SystemTimes; wall-clock times from the system clock are well within range.

Source§

fn from(value: SystemTime) -> Self

Converts to this type from the input type.
Source§

impl From<Timestamp> for SystemTime

Available on crate feature std only.

Converts a Timestamp back into a SystemTime by adding (or subtracting) its offset from the Unix epoch.

Source§

fn from(value: Timestamp) -> Self

Converts to this type from the input type.
Source§

impl FromStr for Timestamp

Source§

type Err = TimestampError

The associated error which can be returned from parsing.
Source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl Hash for Timestamp

Source§

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

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

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

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for Timestamp

Source§

fn cmp(&self, other: &Timestamp) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

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

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

impl PartialEq for Timestamp

Source§

fn eq(&self, other: &Timestamp) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

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

impl PartialOrd for Timestamp

Source§

fn partial_cmp(&self, other: &Timestamp) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Serialize for Timestamp

Available on crate feature serde only.
Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl TryFrom<(i64, u32)> for Timestamp

Source§

type Error = TimestampError

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

fn try_from(value: (i64, u32)) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl Copy for Timestamp

Source§

impl Eq for Timestamp

Source§

impl StructuralPartialEq for Timestamp

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

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

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

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

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

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

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

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

fn clone_into(&self, target: &mut T)

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

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

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

Source§

type Error = <U as TryFrom<T>>::Error

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

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,