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);
This type differs from chrono::DateTime
in that it serializes to and deserializes from a
BSON datetime rather than an RFC 3339 formatted string. Additionally, in non-BSON formats, it
will serialize to and deserialize from that format’s equivalent of the
extended JSON representation of a datetime.
To serialize a chrono::DateTime
as a BSON datetime, you can use
crate::serde_helpers::chrono_datetime_as_bson_datetime
.
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>,
}
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
sourceimpl DateTime
impl DateTime
sourcepub const fn from_millis(date: i64) -> Self
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”).
sourcepub fn from_chrono<T: TimeZone>(dt: DateTime<T>) -> Self
Available on crate feature chrono-0_4
only.
pub fn from_chrono<T: TimeZone>(dt: DateTime<T>) -> Self
chrono-0_4
only.Convert the given chrono::DateTime
into a bson::DateTime
, truncating it to millisecond
precision.
sourcepub fn builder() -> DateTimeBuilder
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.
sourcepub fn to_chrono(self) -> DateTime<Utc>
Available on crate feature chrono-0_4
only.
pub fn to_chrono(self) -> DateTime<Utc>
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::MIN_DATETIME
or chrono::MAX_DATETIME
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::MAX_DATETIME)
sourcepub fn from_time_0_3(dt: OffsetDateTime) -> Self
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.
sourcepub fn to_time_0_3(self) -> OffsetDateTime
Available on crate feature time-0_3
only.
pub fn to_time_0_3(self) -> OffsetDateTime
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())
sourcepub fn from_system_time(st: SystemTime) -> Self
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.
sourcepub fn to_system_time(self) -> SystemTime
pub fn to_system_time(self) -> SystemTime
Convert this DateTime
to a std::time::SystemTime
.
sourcepub const fn timestamp_millis(self) -> i64
pub const fn timestamp_millis(self) -> i64
Returns the number of non-leap-milliseconds since January 1, 1970 UTC.
sourcepub fn to_rfc3339_string(self) -> String
👎 Deprecated since 2.3.0: Use try_to_rfc3339_string instead.
pub fn to_rfc3339_string(self) -> String
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.
sourcepub fn try_to_rfc3339_string(self) -> Result<String>
pub fn try_to_rfc3339_string(self) -> Result<String>
Convert this DateTime
to an RFC 3339 formatted string.
Trait Implementations
sourceimpl<'de> Deserialize<'de> for DateTime
impl<'de> Deserialize<'de> for DateTime
sourcefn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where
D: Deserializer<'de>,
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where
D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
sourceimpl<'de> DeserializeAs<'de, DateTime<Utc>> for DateTime
Available on crate features chrono-0_4
and serde_with
only.
impl<'de> DeserializeAs<'de, DateTime<Utc>> for DateTime
chrono-0_4
and serde_with
only.sourcefn deserialize_as<D>(deserializer: D) -> Result<DateTime<Utc>, D::Error> where
D: Deserializer<'de>,
fn deserialize_as<D>(deserializer: D) -> Result<DateTime<Utc>, D::Error> where
D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer.
sourceimpl<'de> DeserializeAs<'de, OffsetDateTime> for DateTime
Available on crate features time-0_3
and serde_with
only.
impl<'de> DeserializeAs<'de, OffsetDateTime> for DateTime
time-0_3
and serde_with
only.sourcefn deserialize_as<D>(deserializer: D) -> Result<OffsetDateTime, D::Error> where
D: Deserializer<'de>,
fn deserialize_as<D>(deserializer: D) -> Result<OffsetDateTime, D::Error> where
D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer.
sourceimpl From<DateTime> for OffsetDateTime
Available on crate feature time-0_3
only.
impl From<DateTime> for OffsetDateTime
time-0_3
only.sourceimpl<'a> From<DateTime> for RawBsonRef<'a>
impl<'a> From<DateTime> for RawBsonRef<'a>
sourceimpl From<DateTime> for SystemTime
impl From<DateTime> for SystemTime
sourceimpl From<OffsetDateTime> for DateTime
Available on crate feature time-0_3
only.
impl From<OffsetDateTime> for DateTime
time-0_3
only.sourcefn from(x: OffsetDateTime) -> Self
fn from(x: OffsetDateTime) -> Self
Converts to this type from the input type.
sourceimpl From<SystemTime> for DateTime
impl From<SystemTime> for DateTime
sourcefn from(st: SystemTime) -> Self
fn from(st: SystemTime) -> Self
Converts to this type from the input type.
sourceimpl Ord for DateTime
impl Ord for DateTime
1.21.0 · sourcefn max(self, other: Self) -> Self
fn max(self, other: Self) -> Self
Compares and returns the maximum of two values. Read more
1.21.0 · sourcefn min(self, other: Self) -> Self
fn min(self, other: Self) -> Self
Compares and returns the minimum of two values. Read more
1.50.0 · sourcefn clamp(self, min: Self, max: Self) -> Self where
Self: PartialOrd<Self>,
fn clamp(self, min: Self, max: Self) -> Self where
Self: PartialOrd<Self>,
Restrict a value to a certain interval. Read more
sourceimpl PartialOrd<DateTime> for DateTime
impl PartialOrd<DateTime> for DateTime
sourcefn partial_cmp(&self, other: &DateTime) -> Option<Ordering>
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 · sourcefn lt(&self, other: &Rhs) -> bool
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 · sourcefn le(&self, other: &Rhs) -> bool
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
sourceimpl SerializeAs<DateTime<Utc>> for DateTime
Available on crate feature chrono-0_4
only.
impl SerializeAs<DateTime<Utc>> for DateTime
chrono-0_4
only.sourcefn serialize_as<S>(
source: &DateTime<Utc>,
serializer: S
) -> Result<S::Ok, S::Error> where
S: Serializer,
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.
sourceimpl SerializeAs<OffsetDateTime> for DateTime
Available on crate features time-0_3
and chrono-0_4
only.
impl SerializeAs<OffsetDateTime> for DateTime
time-0_3
and chrono-0_4
only.sourcefn serialize_as<S>(
source: &OffsetDateTime,
serializer: S
) -> Result<S::Ok, S::Error> where
S: Serializer,
fn serialize_as<S>(
source: &OffsetDateTime,
serializer: S
) -> Result<S::Ok, S::Error> where
S: Serializer,
Serialize this value into the given Serde serializer.
impl Copy for DateTime
impl Eq for DateTime
impl StructuralEq for DateTime
impl StructuralPartialEq for DateTime
Auto Trait Implementations
impl RefUnwindSafe for DateTime
impl Send for DateTime
impl Sync for DateTime
impl Unpin for DateTime
impl UnwindSafe for DateTime
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> CallHasher for T where
T: Hash + ?Sized,
impl<T> CallHasher for T where
T: Hash + ?Sized,
sourceimpl<Q, K> Equivalent<K> for Q where
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
impl<Q, K> Equivalent<K> for Q where
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
sourcefn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
Compare self to key
and return true
if they are equal.