pub struct DateTime(/* private fields */);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-3 feature flag
The serde_with-3 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-3
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_3::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
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::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)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 const fn saturating_add_millis(self, millis: i64) -> Self
pub const fn saturating_add_millis(self, millis: i64) -> Self
Adds millis milliseconds to the DateTime saturating at DateTime::MIN and
DateTime::MAX.
Sourcepub const fn saturating_add_duration(self, duration: Duration) -> Self
pub const fn saturating_add_duration(self, duration: Duration) -> Self
Adds duration to the DateTime saturating at DateTime::MAX.
As DateTime only have millisecond-precision this will only use the whole milliseconds
of duration.
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
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.
Sourcepub fn parse_rfc3339_str(s: impl AsRef<str>) -> Result<Self>
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.
Sourcepub fn checked_duration_since(self, earlier: Self) -> Option<Duration>
pub fn checked_duration_since(self, earlier: Self) -> Option<Duration>
Returns the time elapsed since earlier, or None if the given DateTime is later than
this one.
Sourcepub fn saturating_duration_since(self, earlier: Self) -> Duration
pub fn saturating_duration_since(self, earlier: Self) -> Duration
Returns the time elapsed since earlier, or a Duration of zero if the given DateTime
is later than this one.
Trait Implementations§
Source§impl<'de> Deserialize<'de> for DateTime
impl<'de> Deserialize<'de> for DateTime
Source§fn 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>,
Source§impl<'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.Source§fn 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>,
Source§impl<'de> DeserializeAs<'de, DateTime<Utc>> for DateTime
Available on crate features chrono-0_4 and serde_with-3 only.
impl<'de> DeserializeAs<'de, DateTime<Utc>> for DateTime
chrono-0_4 and serde_with-3 only.Source§fn 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>,
Source§impl<'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.Source§fn 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>,
Source§impl<'de> DeserializeAs<'de, OffsetDateTime> for DateTime
Available on crate features time-0_3 and serde_with-3 only.
impl<'de> DeserializeAs<'de, OffsetDateTime> for DateTime
time-0_3 and serde_with-3 only.Source§fn 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>,
Source§impl From<DateTime> for OffsetDateTime
Available on crate feature time-0_3 only.
impl From<DateTime> for OffsetDateTime
time-0_3 only.Source§impl From<DateTime> for RawBsonRef<'_>
impl From<DateTime> for RawBsonRef<'_>
Source§impl From<DateTime> for SystemTime
impl From<DateTime> for SystemTime
Source§impl From<OffsetDateTime> for DateTime
Available on crate feature time-0_3 only.
impl From<OffsetDateTime> for DateTime
time-0_3 only.Source§fn from(x: OffsetDateTime) -> Self
fn from(x: OffsetDateTime) -> Self
Source§impl From<SystemTime> for DateTime
impl From<SystemTime> for DateTime
Source§fn from(st: SystemTime) -> Self
fn from(st: SystemTime) -> Self
Source§impl Ord for DateTime
impl Ord for DateTime
Source§impl PartialOrd for DateTime
impl PartialOrd for DateTime
Source§impl SerializeAs<DateTime<Utc>> for DateTime
Available on crate feature chrono-0_4 only.
impl SerializeAs<DateTime<Utc>> for DateTime
chrono-0_4 only.Source§fn 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,
Source§impl SerializeAs<DateTime<Utc>> for DateTime
Available on crate feature chrono-0_4 only.
impl SerializeAs<DateTime<Utc>> for DateTime
chrono-0_4 only.Source§fn 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,
Source§impl 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.Source§fn 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,
Source§impl 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.Source§fn 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,
impl Copy for DateTime
impl Eq for DateTime
impl StructuralPartialEq for DateTime
Auto Trait Implementations§
impl Freeze for DateTime
impl RefUnwindSafe for DateTime
impl Send for DateTime
impl Sync for DateTime
impl Unpin for DateTime
impl UnwindSafe for DateTime
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<Q, K> Comparable<K> for Q
impl<Q, K> Comparable<K> for Q
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.Source§impl<T> FmtForward for T
impl<T> FmtForward for T
Source§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self to use its Binary implementation when Debug-formatted.Source§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self to use its Display implementation when
Debug-formatted.Source§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self to use its LowerExp implementation when
Debug-formatted.Source§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self to use its LowerHex implementation when
Debug-formatted.Source§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self to use its Octal implementation when Debug-formatted.Source§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self to use its Pointer implementation when
Debug-formatted.Source§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self to use its UpperExp implementation when
Debug-formatted.Source§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self to use its UpperHex implementation when
Debug-formatted.Source§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
Source§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
Source§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read moreSource§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read moreSource§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
Source§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R,
) -> R
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
Source§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
self, then passes self.as_ref() into the pipe function.Source§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
self, then passes self.as_mut() into the pipe
function.Source§fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
self, then passes self.deref() into the pipe function.Source§impl<T> Tap for T
impl<T> Tap for T
Source§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
Borrow<B> of a value. Read moreSource§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
BorrowMut<B> of a value. Read moreSource§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
AsRef<R> view of a value. Read moreSource§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
AsMut<R> view of a value. Read moreSource§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
Deref::Target of a value. Read moreSource§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
Deref::Target of a value. Read moreSource§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap() only in debug builds, and is erased in release builds.Source§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut() only in debug builds, and is erased in release
builds.Source§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
.tap_borrow() only in debug builds, and is erased in release
builds.Source§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
.tap_borrow_mut() only in debug builds, and is erased in release
builds.Source§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
.tap_ref() only in debug builds, and is erased in release
builds.Source§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
.tap_ref_mut() only in debug builds, and is erased in release
builds.Source§fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
.tap_deref() only in debug builds, and is erased in release
builds.