Struct bson::datetime::DateTime

source ·
pub struct DateTime(_);
Expand description

Struct representing a BSON datetime. Note: BSON datetimes have millisecond precision.

To enable conversions between this type and chrono::DateTime, enable the "chrono-0_4" feature flag in your Cargo.toml.

use chrono::prelude::*;
let chrono_dt: chrono::DateTime<Utc> = "2014-11-28T12:00:09Z".parse()?;
let bson_dt: bson::DateTime = chrono_dt.into();
let bson_dt = bson::DateTime::from_chrono(chrono_dt);
let back_to_chrono: chrono::DateTime<Utc> = bson_dt.into();
let back_to_chrono = bson_dt.to_chrono();

You may also construct this type from a given year, month, day, and optionally, an hour, minute, second and millisecond, which default to 0 if not explicitly set.

let dt = bson::DateTime::builder().year(1998).month(2).day(12).minute(1).millisecond(23).build()?;
let expected = bson::DateTime::parse_rfc3339_str("1998-02-12T00:01:00.023Z")?;
assert_eq!(dt, expected);

Serde integration

This type differs from chrono::DateTime in that it serializes to and deserializes from a BSON datetime rather than an RFC 3339 formatted string.

e.g.

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct Foo {
    // serializes as a BSON datetime.
    date_time: bson::DateTime,

    // serializes as an RFC 3339 / ISO-8601 string.
    chrono_datetime: chrono::DateTime<chrono::Utc>,
}

let f = Foo { date_time: bson::DateTime::now(), chrono_datetime: chrono::Utc::now() };
println!("{:?}", bson::to_document(&f)?);

Produces the following output:

{ "date_time": DateTime("2023-01-23 20:11:47.316 +00:00:00"), "chrono_datetime": "2023-01-23T20:11:47.316114543Z" }

Additionally, in non-BSON formats, it will serialize to and deserialize from that format’s equivalent of the extended JSON representation of a datetime.

e.g.

let f = Foo { date_time: bson::DateTime::now(), chrono_datetime: chrono::Utc::now() };
println!("{}", serde_json::to_string(&f)?);

Produces the following output:

{"date_time":{"$date":{"$numberLong":"1674504029491"}},"chrono_datetime":"2023-01-23T20:00:29.491791120Z"}

serde_helpers

The bson crate provides a number of useful helpers for serializing and deserializing various datetime types to and from different formats. For example, to serialize a chrono::DateTime as a BSON datetime, you can use crate::serde_helpers::chrono_datetime_as_bson_datetime. Similarly, to serialize a BSON DateTime to a string, you can use crate::serde_helpers::bson_datetime_as_rfc3339_string. Check out the crate::serde_helpers module documentation for a list of all of the helpers offered by the crate.

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct Foo {
    // serializes as a BSON datetime.
    date_time: bson::DateTime,

    // serializes as an RFC 3339 / ISO-8601 string.
    chrono_datetime: chrono::DateTime<chrono::Utc>,

    // serializes as a BSON datetime.
    // this requires the "chrono-0_4" feature flag
    #[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]
    chrono_as_bson: chrono::DateTime<chrono::Utc>,

    // serializes as an RFC 3339 / ISO-8601 string.
    #[serde(with = "bson::serde_helpers::bson_datetime_as_rfc3339_string")]
    bson_as_string: bson::DateTime,
}

The serde_with feature flag

The serde_with feature can be enabled to support more ergonomic serde attributes for (de)serializing chrono::DateTime from/to BSON via the serde_with crate. The main benefit of this compared to the regular serde_helpers is that serde_with can handle nested chrono::DateTime values (e.g. in Option), whereas the former only works on fields that are exactly chrono::DateTime.

use serde::{Deserialize, Serialize};
use bson::doc;

#[serde_with::serde_as]
#[derive(Deserialize, Serialize, PartialEq, Debug)]
struct Foo {
  /// Serializes as a BSON datetime rather than using [`chrono::DateTime`]'s serialization
  #[serde_as(as = "Option<bson::DateTime>")]
  as_bson: Option<chrono::DateTime<chrono::Utc>>,
}

let dt = chrono::Utc::now();
let foo = Foo {
  as_bson: Some(dt),
};

let expected = doc! {
  "as_bson": bson::DateTime::from_chrono(dt),
};

assert_eq!(bson::to_document(&foo)?, expected);

Implementations§

source§

impl DateTime

source

pub const MAX: Self = _

The latest possible date that can be represented in BSON.

source

pub const MIN: Self = _

The earliest possible date that can be represented in BSON.

source

pub const fn from_millis(date: i64) -> Self

Makes a new DateTime from the number of non-leap milliseconds since January 1, 1970 0:00:00 UTC (aka “UNIX timestamp”).

source

pub fn now() -> DateTime

Returns a DateTime which corresponds to the current date and time.

source

pub fn from_chrono<T: TimeZone>(dt: DateTime<T>) -> Self

Available on crate feature chrono-0_4 only.

Convert the given chrono::DateTime into a bson::DateTime, truncating it to millisecond precision.

source

pub fn builder() -> DateTimeBuilder

Returns a builder used to construct a DateTime from a given year, month, day, and optionally, an hour, minute, second and millisecond, which default to 0 if not explicitly set.

Note: You cannot call build() before setting at least the year, month and day.

source

pub fn to_chrono(self) -> DateTime<Utc>

Available on crate feature chrono-0_4 only.

Convert this DateTime to a chrono::DateTime<Utc>.

Note: Not every BSON datetime can be represented as a chrono::DateTime. For such dates, chrono::DateTime::MIN_UTC or chrono::DateTime::MAX_UTC will be returned, whichever is closer.

let bson_dt = bson::DateTime::now();
let chrono_dt = bson_dt.to_chrono();
assert_eq!(bson_dt.timestamp_millis(), chrono_dt.timestamp_millis());

let big = bson::DateTime::from_millis(i64::MAX);
let chrono_big = big.to_chrono();
assert_eq!(chrono_big, chrono::DateTime::<chrono::Utc>::MAX_UTC)
source

pub fn from_time_0_3(dt: OffsetDateTime) -> Self

Convert the given time::OffsetDateTime into a bson::DateTime, truncating it to millisecond precision.

If the provided time is too far in the future or too far in the past to be represented by a BSON datetime, either DateTime::MAX or DateTime::MIN will be returned, whichever is closer.

source

pub fn to_time_0_3(self) -> OffsetDateTime

Available on crate feature time-0_3 only.

Convert this DateTime to a time::OffsetDateTime.

Note: Not every BSON datetime can be represented as a time::OffsetDateTime. For such dates, time::PrimitiveDateTime::MIN or time::PrimitiveDateTime::MAX will be returned, whichever is closer.

let bson_dt = bson::DateTime::now();
let time_dt = bson_dt.to_time_0_3();
assert_eq!(bson_dt.timestamp_millis() / 1000, time_dt.unix_timestamp());

let big = bson::DateTime::from_millis(i64::MIN);
let time_big = big.to_time_0_3();
assert_eq!(time_big, time::PrimitiveDateTime::MIN.assume_utc())
source

pub fn from_system_time(st: SystemTime) -> Self

Convert the given std::time::SystemTime to a DateTime.

If the provided time is too far in the future or too far in the past to be represented by a BSON datetime, either DateTime::MAX or DateTime::MIN will be returned, whichever is closer.

source

pub fn to_system_time(self) -> SystemTime

Convert this DateTime to a std::time::SystemTime.

source

pub const fn timestamp_millis(self) -> i64

Returns the number of non-leap-milliseconds since January 1, 1970 UTC.

source

pub fn to_rfc3339_string(self) -> String

👎Deprecated since 2.3.0: Use try_to_rfc3339_string instead.

Convert this DateTime to an RFC 3339 formatted string. Panics if it could not be represented in that format.

source

pub fn try_to_rfc3339_string(self) -> Result<String>

Convert this DateTime to an RFC 3339 formatted string.

source

pub fn parse_rfc3339_str(s: impl AsRef<str>) -> Result<Self>

Convert the given RFC 3339 formatted string to a DateTime, truncating it to millisecond precision.

Trait Implementations§

source§

impl Clone for DateTime

source§

fn clone(&self) -> DateTime

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

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

Performs copy-assignment from source. Read more
source§

impl Debug for DateTime

source§

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

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

impl<'de> Deserialize<'de> for DateTime

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<'de> DeserializeAs<'de, DateTime<Utc>> for DateTime

Available on crate features chrono-0_4 and serde_with only.
source§

fn deserialize_as<D>(deserializer: D) -> Result<DateTime<Utc>, D::Error>where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer.
source§

impl<'de> DeserializeAs<'de, OffsetDateTime> for DateTime

Available on crate features time-0_3 and serde_with only.
source§

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

Deserialize this value from the given Serde deserializer.
source§

impl Display for DateTime

source§

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

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

impl<T: TimeZone> From<DateTime<T>> for DateTime

Available on crate feature chrono-0_4 only.
source§

fn from(x: DateTime<T>) -> Self

Converts to this type from the input type.
source§

impl From<DateTime> for Bson

source§

fn from(dt: DateTime) -> Self

Converts to this type from the input type.
source§

impl From<DateTime> for DateTime<Utc>

Available on crate feature chrono-0_4 only.
source§

fn from(bson_dt: DateTime) -> Self

Converts to this type from the input type.
source§

impl From<DateTime> for OffsetDateTime

Available on crate feature time-0_3 only.
source§

fn from(bson_dt: DateTime) -> Self

Converts to this type from the input type.
source§

impl From<DateTime> for RawBson

source§

fn from(dt: DateTime) -> Self

Converts to this type from the input type.
source§

impl<'a> From<DateTime> for RawBsonRef<'a>

source§

fn from(dt: DateTime) -> Self

Converts to this type from the input type.
source§

impl From<DateTime> for SystemTime

source§

fn from(dt: DateTime) -> Self

Converts to this type from the input type.
source§

impl From<OffsetDateTime> for DateTime

Available on crate feature time-0_3 only.
source§

fn from(x: OffsetDateTime) -> Self

Converts to this type from the input type.
source§

impl From<SystemTime> for DateTime

source§

fn from(st: SystemTime) -> Self

Converts to this type from the input type.
source§

impl Hash for DateTime

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 DateTime

source§

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

This method returns an Ordering between self and other. Read more
1.21.0 · source§

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

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

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

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

fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>,

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

impl PartialEq<DateTime> for DateTime

source§

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

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd<DateTime> for DateTime

source§

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

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

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

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

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

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

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

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

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

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl Serialize for DateTime

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 SerializeAs<DateTime<Utc>> for DateTime

Available on crate feature chrono-0_4 only.
source§

fn serialize_as<S>( source: &DateTime<Utc>, serializer: S ) -> Result<S::Ok, S::Error>where S: Serializer,

Serialize this value into the given Serde serializer.
source§

impl SerializeAs<OffsetDateTime> for DateTime

Available on crate features time-0_3 and chrono-0_4 only.
source§

fn serialize_as<S>( source: &OffsetDateTime, serializer: S ) -> Result<S::Ok, S::Error>where S: Serializer,

Serialize this value into the given Serde serializer.
source§

impl Copy for DateTime

source§

impl Eq for DateTime

source§

impl StructuralEq for DateTime

source§

impl StructuralPartialEq for DateTime

Auto Trait Implementations§

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

const: unstable · source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> CallHasher for Twhere T: Hash + ?Sized,

source§

default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher,

§

impl<T> Conv for T

§

fn conv<T>(self) -> Twhere Self: Into<T>,

Converts self into T using Into<T>. Read more
source§

impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
§

impl<T> FmtForward for T

§

fn fmt_binary(self) -> FmtBinary<Self>where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
§

fn fmt_display(self) -> FmtDisplay<Self>where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
§

fn fmt_octal(self) -> FmtOctal<Self>where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
§

fn fmt_pointer(self) -> FmtPointer<Self>where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
§

fn fmt_list(self) -> FmtList<Self>where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

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

const: unstable · 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.

§

impl<T> Pipe for Twhere T: ?Sized,

§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> Rwhere Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R ) -> Rwhere Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> Rwhere Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> Rwhere Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> Rwhere Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R ) -> Rwhere Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
§

impl<T> Tap for T

§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Selfwhere Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Selfwhere Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Selfwhere Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Selfwhere Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Selfwhere Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Selfwhere Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Selfwhere Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Selfwhere Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
source§

impl<T> ToOwned for Twhere T: Clone,

§

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 Twhere T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
§

impl<T> TryConv for T

§

fn try_conv<T>(self) -> Result<T, Self::Error>where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
source§

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

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.
source§

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

§

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

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V

source§

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