| 1 |
//! Module containing functionality related to BSON DateTimes. |
| 2 |
//! For more information, see the documentation for the [`DateTime`] type. |
| 3 |
|
| 4 |
use std::{ |
| 5 |
convert::TryInto, |
| 6 |
error, |
| 7 |
fmt::{self, Display}, |
| 8 |
result, |
| 9 |
time::{Duration, SystemTime}, |
| 10 |
}; |
| 11 |
|
| 12 |
pub(crate) mod builder; |
| 13 |
pub use crate::datetime::builder::DateTimeBuilder; |
| 14 |
use time::format_description::well_known::Rfc3339; |
| 15 |
|
| 16 |
#[cfg(feature = "chrono-0_4")] |
| 17 |
use chrono::{LocalResult, TimeZone, Utc}; |
| 18 |
#[cfg(all( |
| 19 |
any(feature = "serde_with", feature = "serde_with-3"), |
| 20 |
any(feature = "chrono-0_4", feature = "time-0_3") |
| 21 |
))] |
| 22 |
use serde::{Deserialize, Deserializer, Serialize}; |
| 23 |
#[cfg(all( |
| 24 |
feature = "serde_with", |
| 25 |
any(feature = "chrono-0_4", feature = "time-0_3") |
| 26 |
))] |
| 27 |
use serde_with::{DeserializeAs, SerializeAs}; |
| 28 |
|
| 29 |
/// Struct representing a BSON datetime. |
| 30 |
/// Note: BSON datetimes have millisecond precision. |
| 31 |
/// |
| 32 |
/// To enable conversions between this type and [`chrono::DateTime`], enable the `"chrono-0_4"` |
| 33 |
/// feature flag in your `Cargo.toml`. |
| 34 |
/// ``` |
| 35 |
/// use chrono::prelude::*; |
| 36 |
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> { |
| 37 |
/// # #[cfg(feature = "chrono-0_4")] |
| 38 |
/// # { |
| 39 |
/// let chrono_dt: chrono::DateTime<Utc> = "2014-11-28T12:00:09Z".parse()?; |
| 40 |
/// let bson_dt: bson::DateTime = chrono_dt.into(); |
| 41 |
/// let bson_dt = bson::DateTime::from_chrono(chrono_dt); |
| 42 |
/// let back_to_chrono: chrono::DateTime<Utc> = bson_dt.into(); |
| 43 |
/// let back_to_chrono = bson_dt.to_chrono(); |
| 44 |
/// # } |
| 45 |
/// # Ok(()) |
| 46 |
/// # } |
| 47 |
/// ``` |
| 48 |
/// |
| 49 |
/// You may also construct this type from a given `year`, `month`, `day`, and optionally, |
| 50 |
/// an `hour`, `minute`, `second` and `millisecond`, which default to 0 if not explicitly set. |
| 51 |
/// |
| 52 |
/// ``` |
| 53 |
/// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 54 |
/// let dt = bson::DateTime::builder().year(1998).month(2).day(12).minute(1).millisecond(23).build()?; |
| 55 |
/// let expected = bson::DateTime::parse_rfc3339_str("1998-02-12T00:01:00.023Z")?; |
| 56 |
/// assert_eq!(dt, expected); |
| 57 |
/// # Ok(()) |
| 58 |
/// # } |
| 59 |
/// ``` |
| 60 |
/// |
| 61 |
/// ## Serde integration |
| 62 |
/// |
| 63 |
/// This type differs from [`chrono::DateTime`] in that it serializes to and deserializes from a |
| 64 |
/// BSON datetime rather than an RFC 3339 formatted string. |
| 65 |
/// |
| 66 |
/// e.g. |
| 67 |
/// ```rust |
| 68 |
/// use serde::{Serialize, Deserialize}; |
| 69 |
/// |
| 70 |
/// #[derive(Serialize, Deserialize)] |
| 71 |
/// struct Foo { |
| 72 |
/// // serializes as a BSON datetime. |
| 73 |
/// date_time: bson::DateTime, |
| 74 |
/// |
| 75 |
/// // serializes as an RFC 3339 / ISO-8601 string. |
| 76 |
/// chrono_datetime: chrono::DateTime<chrono::Utc>, |
| 77 |
/// } |
| 78 |
/// |
| 79 |
/// # fn main() -> bson::ser::Result<()> { |
| 80 |
/// let f = Foo { date_time: bson::DateTime::now(), chrono_datetime: chrono::Utc::now() }; |
| 81 |
/// println!("{:?}", bson::to_document(&f)?); |
| 82 |
/// # Ok(()) |
| 83 |
/// # } |
| 84 |
/// ``` |
| 85 |
/// Produces the following output: |
| 86 |
/// ```js |
| 87 |
/// { "date_time": DateTime("2023-01-23 20:11:47.316 +00:00:00"), "chrono_datetime": "2023-01-23T20:11:47.316114543Z" } |
| 88 |
/// ``` |
| 89 |
/// |
| 90 |
/// Additionally, in non-BSON formats, it will serialize to and deserialize from that format's |
| 91 |
/// equivalent of the [extended JSON representation](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/) of a datetime. |
| 92 |
/// |
| 93 |
/// e.g. |
| 94 |
/// ```rust |
| 95 |
/// # use serde::Serialize; |
| 96 |
/// # #[derive(Serialize)] |
| 97 |
/// # struct Foo { |
| 98 |
/// # // serializes as a BSON datetime. |
| 99 |
/// # date_time: bson::DateTime, |
| 100 |
/// # |
| 101 |
/// # // serializes as an RFC 3339 / ISO-8601 string. |
| 102 |
/// # chrono_datetime: chrono::DateTime<chrono::Utc>, |
| 103 |
/// # } |
| 104 |
/// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 105 |
/// let f = Foo { date_time: bson::DateTime::now(), chrono_datetime: chrono::Utc::now() }; |
| 106 |
/// println!("{}", serde_json::to_string(&f)?); |
| 107 |
/// # Ok(()) |
| 108 |
/// # } |
| 109 |
/// ``` |
| 110 |
/// Produces the following output: |
| 111 |
/// ```js |
| 112 |
/// {"date_time":{"$date":{"$numberLong":"1674504029491"}},"chrono_datetime":"2023-01-23T20:00:29.491791120Z"} |
| 113 |
/// ``` |
| 114 |
/// |
| 115 |
/// ### `serde_helpers` |
| 116 |
/// The `bson` crate provides a number of useful helpers for serializing and deserializing |
| 117 |
/// various datetime types to and from different formats. For example, to serialize a |
| 118 |
/// [`chrono::DateTime`] as a BSON datetime, you can use |
| 119 |
/// [`crate::serde_helpers::chrono_datetime_as_bson_datetime`]. Similarly, to serialize a BSON |
| 120 |
/// [`DateTime`] to a string, you can use [`crate::serde_helpers::bson_datetime_as_rfc3339_string`]. |
| 121 |
/// Check out the [`crate::serde_helpers`] module documentation for a list of all of the helpers |
| 122 |
/// offered by the crate. |
| 123 |
/// |
| 124 |
/// ```rust |
| 125 |
/// # #[cfg(feature = "chrono-0_4")] |
| 126 |
/// # { |
| 127 |
/// use serde::{Serialize, Deserialize}; |
| 128 |
/// |
| 129 |
/// #[derive(Serialize, Deserialize)] |
| 130 |
/// struct Foo { |
| 131 |
/// // serializes as a BSON datetime. |
| 132 |
/// date_time: bson::DateTime, |
| 133 |
/// |
| 134 |
/// // serializes as an RFC 3339 / ISO-8601 string. |
| 135 |
/// chrono_datetime: chrono::DateTime<chrono::Utc>, |
| 136 |
/// |
| 137 |
/// // serializes as a BSON datetime. |
| 138 |
/// // this requires the "chrono-0_4" feature flag |
| 139 |
/// #[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")] |
| 140 |
/// chrono_as_bson: chrono::DateTime<chrono::Utc>, |
| 141 |
/// |
| 142 |
/// // serializes as an RFC 3339 / ISO-8601 string. |
| 143 |
/// #[serde(with = "bson::serde_helpers::bson_datetime_as_rfc3339_string")] |
| 144 |
/// bson_as_string: bson::DateTime, |
| 145 |
/// } |
| 146 |
/// # } |
| 147 |
/// ``` |
| 148 |
/// ### The `serde_with-3` feature flag |
| 149 |
/// |
| 150 |
/// The `serde_with-3` feature can be enabled to support more ergonomic serde attributes for |
| 151 |
/// (de)serializing [`chrono::DateTime`] from/to BSON via the [`serde_with`](https://docs.rs/serde_with/1.11.0/serde_with/) |
| 152 |
/// crate. The main benefit of this compared to the regular `serde_helpers` is that `serde_with-3` |
| 153 |
/// can handle nested [`chrono::DateTime`] values (e.g. in [`Option`]), whereas the former only |
| 154 |
/// works on fields that are exactly [`chrono::DateTime`]. |
| 155 |
/// ``` |
| 156 |
/// # #[cfg(all(feature = "chrono-0_4", feature = "serde_with-3"))] |
| 157 |
/// # { |
| 158 |
/// use serde::{Deserialize, Serialize}; |
| 159 |
/// use bson::doc; |
| 160 |
/// |
| 161 |
/// #[serde_with_3::serde_as] |
| 162 |
/// #[derive(Deserialize, Serialize, PartialEq, Debug)] |
| 163 |
/// struct Foo { |
| 164 |
/// /// Serializes as a BSON datetime rather than using [`chrono::DateTime`]'s serialization |
| 165 |
/// #[serde_as(as = "Option<bson::DateTime>")] |
| 166 |
/// as_bson: Option<chrono::DateTime<chrono::Utc>>, |
| 167 |
/// } |
| 168 |
/// |
| 169 |
/// let dt = chrono::Utc::now(); |
| 170 |
/// let foo = Foo { |
| 171 |
/// as_bson: Some(dt), |
| 172 |
/// }; |
| 173 |
/// |
| 174 |
/// let expected = doc! { |
| 175 |
/// "as_bson": bson::DateTime::from_chrono(dt), |
| 176 |
/// }; |
| 177 |
/// |
| 178 |
/// assert_eq!(bson::to_document(&foo)?, expected); |
| 179 |
/// # } |
| 180 |
/// # Ok::<(), Box<dyn std::error::Error>>(()) |
| 181 |
/// ``` |
| 182 |
#[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)] |
| 183 |
pub struct DateTime(i64); |
| 184 |
|
| 185 |
impl crate::DateTime { |
| 186 |
/// The latest possible date that can be represented in BSON. |
| 187 |
pub const MAX: Self = Self::from_millis(i64::MAX); |
| 188 |
|
| 189 |
/// The earliest possible date that can be represented in BSON. |
| 190 |
pub const MIN: Self = Self::from_millis(i64::MIN); |
| 191 |
|
| 192 |
/// Makes a new [`DateTime`] from the number of non-leap milliseconds since |
| 193 |
/// January 1, 1970 0:00:00 UTC (aka "UNIX timestamp"). |
| 194 |
pub const fn from_millis(date: i64) -> Self { |
| 195 |
Self(date) |
| 196 |
} |
| 197 |
|
| 198 |
/// Returns a [`DateTime`] which corresponds to the current date and time. |
| 199 |
pub fn now() -> DateTime { |
| 200 |
Self::from_system_time(SystemTime::now()) |
| 201 |
} |
| 202 |
|
| 203 |
/// Convert the given [`chrono::DateTime`] into a [`bson::DateTime`](DateTime), truncating it to |
| 204 |
/// millisecond precision. |
| 205 |
#[cfg(feature = "chrono-0_4")] |
| 206 |
#[cfg_attr(docsrs, doc(cfg(feature = "chrono-0_4")))] |
| 207 |
pub fn from_chrono<T: chrono::TimeZone>(dt: chrono::DateTime<T>) -> Self { |
| 208 |
Self::from_millis(dt.timestamp_millis()) |
| 209 |
} |
| 210 |
|
| 211 |
/// Returns a builder used to construct a [`DateTime`] from a given year, month, |
| 212 |
/// day, and optionally, an hour, minute, second and millisecond, which default to |
| 213 |
/// 0 if not explicitly set. |
| 214 |
/// |
| 215 |
/// Note: You cannot call `build()` before setting at least the year, month and day. |
| 216 |
pub fn builder() -> DateTimeBuilder { |
| 217 |
DateTimeBuilder::default() |
| 218 |
} |
| 219 |
|
| 220 |
/// Convert this [`DateTime`] to a [`chrono::DateTime<Utc>`]. |
| 221 |
/// |
| 222 |
/// Note: Not every BSON datetime can be represented as a [`chrono::DateTime`]. For such dates, |
| 223 |
/// [`chrono::DateTime::MIN_UTC`] or [`chrono::DateTime::MAX_UTC`] will be returned, whichever |
| 224 |
/// is closer. |
| 225 |
/// |
| 226 |
/// ``` |
| 227 |
/// let bson_dt = bson::DateTime::now(); |
| 228 |
/// let chrono_dt = bson_dt.to_chrono(); |
| 229 |
/// assert_eq!(bson_dt.timestamp_millis(), chrono_dt.timestamp_millis()); |
| 230 |
/// |
| 231 |
/// let big = bson::DateTime::from_millis(i64::MAX); |
| 232 |
/// let chrono_big = big.to_chrono(); |
| 233 |
/// assert_eq!(chrono_big, chrono::DateTime::<chrono::Utc>::MAX_UTC) |
| 234 |
/// ``` |
| 235 |
#[cfg(feature = "chrono-0_4")] |
| 236 |
#[cfg_attr(docsrs, doc(cfg(feature = "chrono-0_4")))] |
| 237 |
pub fn to_chrono(self) -> chrono::DateTime<Utc> { |
| 238 |
match Utc.timestamp_millis_opt(self.0) { |
| 239 |
LocalResult::Single(dt) => dt, |
| 240 |
_ => { |
| 241 |
if self.0 < 0 { |
| 242 |
chrono::DateTime::<Utc>::MIN_UTC |
| 243 |
} else { |
| 244 |
chrono::DateTime::<Utc>::MAX_UTC |
| 245 |
} |
| 246 |
} |
| 247 |
} |
| 248 |
} |
| 249 |
|
| 250 |
fn from_time_private(dt: time::OffsetDateTime) -> Self { |
| 251 |
let millis = dt.unix_timestamp_nanos() / 1_000_000; |
| 252 |
match millis.try_into() { |
| 253 |
Ok(ts) => Self::from_millis(ts), |
| 254 |
_ => { |
| 255 |
if millis > 0 { |
| 256 |
Self::MAX |
| 257 |
} else { |
| 258 |
Self::MIN |
| 259 |
} |
| 260 |
} |
| 261 |
} |
| 262 |
} |
| 263 |
|
| 264 |
#[cfg(not(feature = "time-0_3"))] |
| 265 |
#[allow(unused)] |
| 266 |
pub(crate) fn from_time_0_3(dt: time::OffsetDateTime) -> Self { |
| 267 |
Self::from_time_private(dt) |
| 268 |
} |
| 269 |
|
| 270 |
/// Convert the given [`time::OffsetDateTime`] into a [`bson::DateTime`](DateTime), truncating |
| 271 |
/// it to millisecond precision. |
| 272 |
/// |
| 273 |
/// If the provided time is too far in the future or too far in the past to be represented |
| 274 |
/// by a BSON datetime, either [`DateTime::MAX`] or [`DateTime::MIN`] will be |
| 275 |
/// returned, whichever is closer. |
| 276 |
#[cfg(feature = "time-0_3")] |
| 277 |
pub fn from_time_0_3(dt: time::OffsetDateTime) -> Self { |
| 278 |
Self::from_time_private(dt) |
| 279 |
} |
| 280 |
|
| 281 |
fn to_time_private(self) -> time::OffsetDateTime { |
| 282 |
match self.to_time_opt() { |
| 283 |
Some(dt) => dt, |
| 284 |
None => if self.0 < 0 { |
| 285 |
time::PrimitiveDateTime::MIN |
| 286 |
} else { |
| 287 |
time::PrimitiveDateTime::MAX |
| 288 |
} |
| 289 |
.assume_utc(), |
| 290 |
} |
| 291 |
} |
| 292 |
|
| 293 |
pub(crate) fn to_time_opt(self) -> Option<time::OffsetDateTime> { |
| 294 |
time::OffsetDateTime::UNIX_EPOCH.checked_add(time::Duration::milliseconds(self.0)) |
| 295 |
} |
| 296 |
|
| 297 |
#[cfg(not(feature = "time-0_3"))] |
| 298 |
#[allow(unused)] |
| 299 |
pub(crate) fn to_time_0_3(self) -> time::OffsetDateTime { |
| 300 |
self.to_time_private() |
| 301 |
} |
| 302 |
|
| 303 |
/// Convert this [`DateTime`] to a [`time::OffsetDateTime`]. |
| 304 |
/// |
| 305 |
/// Note: Not every BSON datetime can be represented as a [`time::OffsetDateTime`]. For such |
| 306 |
/// dates, [`time::PrimitiveDateTime::MIN`] or [`time::PrimitiveDateTime::MAX`] will be |
| 307 |
/// returned, whichever is closer. |
| 308 |
/// |
| 309 |
/// ``` |
| 310 |
/// let bson_dt = bson::DateTime::now(); |
| 311 |
/// let time_dt = bson_dt.to_time_0_3(); |
| 312 |
/// assert_eq!(bson_dt.timestamp_millis() / 1000, time_dt.unix_timestamp()); |
| 313 |
/// |
| 314 |
/// let big = bson::DateTime::from_millis(i64::MIN); |
| 315 |
/// let time_big = big.to_time_0_3(); |
| 316 |
/// assert_eq!(time_big, time::PrimitiveDateTime::MIN.assume_utc()) |
| 317 |
/// ``` |
| 318 |
#[cfg(feature = "time-0_3")] |
| 319 |
#[cfg_attr(docsrs, doc(cfg(feature = "time-0_3")))] |
| 320 |
pub fn to_time_0_3(self) -> time::OffsetDateTime { |
| 321 |
self.to_time_private() |
| 322 |
} |
| 323 |
|
| 324 |
/// Convert the given [`std::time::SystemTime`] to a [`DateTime`]. |
| 325 |
/// |
| 326 |
/// If the provided time is too far in the future or too far in the past to be represented |
| 327 |
/// by a BSON datetime, either [`DateTime::MAX`] or [`DateTime::MIN`] will be |
| 328 |
/// returned, whichever is closer. |
| 329 |
pub fn from_system_time(st: SystemTime) -> Self { |
| 330 |
match st.duration_since(SystemTime::UNIX_EPOCH) { |
| 331 |
Ok(d) => { |
| 332 |
if d.as_millis() <= i64::MAX as u128 { |
| 333 |
Self::from_millis(d.as_millis() as i64) |
| 334 |
} else { |
| 335 |
Self::MAX |
| 336 |
} |
| 337 |
} |
| 338 |
// handle SystemTime from before the Unix Epoch |
| 339 |
Err(e) => { |
| 340 |
let millis = e.duration().as_millis(); |
| 341 |
if millis > i64::MAX as u128 { |
| 342 |
Self::MIN |
| 343 |
} else { |
| 344 |
Self::from_millis(-(millis as i64)) |
| 345 |
} |
| 346 |
} |
| 347 |
} |
| 348 |
} |
| 349 |
|
| 350 |
/// Convert this [`DateTime`] to a [`std::time::SystemTime`]. |
| 351 |
pub fn to_system_time(self) -> SystemTime { |
| 352 |
if self.0 >= 0 { |
| 353 |
SystemTime::UNIX_EPOCH + Duration::from_millis(self.0 as u64) |
| 354 |
} else { |
| 355 |
// need to convert to i128 before calculating absolute value since i64::MIN.abs() |
| 356 |
// overflows and panics. |
| 357 |
SystemTime::UNIX_EPOCH - Duration::from_millis((self.0 as i128).unsigned_abs() as u64) |
| 358 |
} |
| 359 |
} |
| 360 |
|
| 361 |
/// Returns the number of non-leap-milliseconds since January 1, 1970 UTC. |
| 362 |
pub const fn timestamp_millis(self) -> i64 { |
| 363 |
self.0 |
| 364 |
} |
| 365 |
|
| 366 |
#[deprecated(since = "2.3.0", note = "Use try_to_rfc3339_string instead.")] |
| 367 |
/// Convert this [`DateTime`] to an RFC 3339 formatted string. Panics if it could not be |
| 368 |
/// represented in that format. |
| 369 |
pub fn to_rfc3339_string(self) -> String { |
| 370 |
self.try_to_rfc3339_string().unwrap() |
| 371 |
} |
| 372 |
|
| 373 |
/// Convert this [`DateTime`] to an RFC 3339 formatted string. |
| 374 |
pub fn try_to_rfc3339_string(self) -> Result<String> { |
| 375 |
self.to_time_0_3() |
| 376 |
.format(&Rfc3339) |
| 377 |
.map_err(|e| Error::CannotFormat { |
| 378 |
message: e.to_string(), |
| 379 |
}) |
| 380 |
} |
| 381 |
|
| 382 |
/// Convert the given RFC 3339 formatted string to a [`DateTime`], truncating it to millisecond |
| 383 |
/// precision. |
| 384 |
pub fn parse_rfc3339_str(s: impl AsRef<str>) -> Result<Self> { |
| 385 |
let odt = time::OffsetDateTime::parse(s.as_ref(), &Rfc3339).map_err(|e| { |
| 386 |
Error::InvalidTimestamp { |
| 387 |
message: e.to_string(), |
| 388 |
} |
| 389 |
})?; |
| 390 |
Ok(Self::from_time_0_3(odt)) |
| 391 |
} |
| 392 |
|
| 393 |
/// Returns the time elapsed since `earlier`, or `None` if the given `DateTime` is later than |
| 394 |
/// this one. |
| 395 |
pub fn checked_duration_since(self, earlier: Self) -> Option<Duration> { |
| 396 |
if earlier.0 > self.0 { |
| 397 |
return None; |
| 398 |
} |
| 399 |
Some(Duration::from_millis((self.0 - earlier.0) as u64)) |
| 400 |
} |
| 401 |
|
| 402 |
/// Returns the time elapsed since `earlier`, or a [`Duration`] of zero if the given `DateTime` |
| 403 |
/// is later than this one. |
| 404 |
pub fn saturating_duration_since(self, earlier: Self) -> Duration { |
| 405 |
self.checked_duration_since(earlier) |
| 406 |
.unwrap_or(Duration::ZERO) |
| 407 |
} |
| 408 |
} |
| 409 |
|
| 410 |
impl fmt::Debug for crate::DateTime { |
| 411 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 412 |
let mut tup = f.debug_tuple("DateTime"); |
| 413 |
match self.to_time_opt() { |
| 414 |
Some(dt) => tup.field(&dt), |
| 415 |
_ => tup.field(&self.0), |
| 416 |
}; |
| 417 |
tup.finish() |
| 418 |
} |
| 419 |
} |
| 420 |
|
| 421 |
impl Display for crate::DateTime { |
| 422 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 423 |
match self.to_time_opt() { |
| 424 |
Some(dt) => Display::fmt(&dt, f), |
| 425 |
_ => Display::fmt(&self.0, f), |
| 426 |
} |
| 427 |
} |
| 428 |
} |
| 429 |
|
| 430 |
impl From<SystemTime> for crate::DateTime { |
| 431 |
fn from(st: SystemTime) -> Self { |
| 432 |
Self::from_system_time(st) |
| 433 |
} |
| 434 |
} |
| 435 |
|
| 436 |
impl From<crate::DateTime> for SystemTime { |
| 437 |
fn from(dt: crate::DateTime) -> Self { |
| 438 |
dt.to_system_time() |
| 439 |
} |
| 440 |
} |
| 441 |
|
| 442 |
#[cfg(feature = "chrono-0_4")] |
| 443 |
#[cfg_attr(docsrs, doc(cfg(feature = "chrono-0_4")))] |
| 444 |
impl From<crate::DateTime> for chrono::DateTime<Utc> { |
| 445 |
fn from(bson_dt: DateTime) -> Self { |
| 446 |
bson_dt.to_chrono() |
| 447 |
} |
| 448 |
} |
| 449 |
|
| 450 |
#[cfg(feature = "chrono-0_4")] |
| 451 |
#[cfg_attr(docsrs, doc(cfg(feature = "chrono-0_4")))] |
| 452 |
impl<T: chrono::TimeZone> From<chrono::DateTime<T>> for crate::DateTime { |
| 453 |
fn from(x: chrono::DateTime<T>) -> Self { |
| 454 |
Self::from_chrono(x) |
| 455 |
} |
| 456 |
} |
| 457 |
|
| 458 |
#[cfg(all(feature = "chrono-0_4", feature = "serde_with"))] |
| 459 |
#[cfg_attr(docsrs, doc(cfg(all(feature = "chrono-0_4", feature = "serde_with"))))] |
| 460 |
impl<'de> DeserializeAs<'de, chrono::DateTime<Utc>> for crate::DateTime { |
| 461 |
fn deserialize_as<D>(deserializer: D) -> std::result::Result<chrono::DateTime<Utc>, D::Error> |
| 462 |
where |
| 463 |
D: Deserializer<'de>, |
| 464 |
{ |
| 465 |
let dt = DateTime::deserialize(deserializer)?; |
| 466 |
Ok(dt.to_chrono()) |
| 467 |
} |
| 468 |
} |
| 469 |
|
| 470 |
#[cfg(all(feature = "chrono-0_4", feature = "serde_with"))] |
| 471 |
#[cfg_attr(docsrs, doc(cfg(all(feature = "chrono-0_4", feature = "chrono-0_4"))))] |
| 472 |
impl SerializeAs<chrono::DateTime<Utc>> for crate::DateTime { |
| 473 |
fn serialize_as<S>( |
| 474 |
source: &chrono::DateTime<Utc>, |
| 475 |
serializer: S, |
| 476 |
) -> std::result::Result<S::Ok, S::Error> |
| 477 |
where |
| 478 |
S: serde::Serializer, |
| 479 |
{ |
| 480 |
let dt = DateTime::from_chrono(*source); |
| 481 |
dt.serialize(serializer) |
| 482 |
} |
| 483 |
} |
| 484 |
|
| 485 |
#[cfg(all(feature = "chrono-0_4", feature = "serde_with-3"))] |
| 486 |
#[cfg_attr( |
| 487 |
docsrs, |
| 488 |
doc(cfg(all(feature = "chrono-0_4", feature = "serde_with-3"))) |
| 489 |
)] |
| 490 |
impl<'de> serde_with_3::DeserializeAs<'de, chrono::DateTime<Utc>> for crate::DateTime { |
| 491 |
fn deserialize_as<D>(deserializer: D) -> std::result::Result<chrono::DateTime<Utc>, D::Error> |
| 492 |
where |
| 493 |
D: Deserializer<'de>, |
| 494 |
{ |
| 495 |
let dt = DateTime::deserialize(deserializer)?; |
| 496 |
Ok(dt.to_chrono()) |
| 497 |
} |
| 498 |
} |
| 499 |
|
| 500 |
#[cfg(all(feature = "chrono-0_4", feature = "serde_with-3"))] |
| 501 |
#[cfg_attr(docsrs, doc(cfg(all(feature = "chrono-0_4", feature = "chrono-0_4"))))] |
| 502 |
impl serde_with_3::SerializeAs<chrono::DateTime<Utc>> for crate::DateTime { |
| 503 |
fn serialize_as<S>( |
| 504 |
source: &chrono::DateTime<Utc>, |
| 505 |
serializer: S, |
| 506 |
) -> std::result::Result<S::Ok, S::Error> |
| 507 |
where |
| 508 |
S: serde::Serializer, |
| 509 |
{ |
| 510 |
let dt = DateTime::from_chrono(*source); |
| 511 |
dt.serialize(serializer) |
| 512 |
} |
| 513 |
} |
| 514 |
|
| 515 |
#[cfg(feature = "time-0_3")] |
| 516 |
#[cfg_attr(docsrs, doc(cfg(feature = "time-0_3")))] |
| 517 |
impl From<crate::DateTime> for time::OffsetDateTime { |
| 518 |
fn from(bson_dt: DateTime) -> Self { |
| 519 |
bson_dt.to_time_0_3() |
| 520 |
} |
| 521 |
} |
| 522 |
|
| 523 |
#[cfg(feature = "time-0_3")] |
| 524 |
#[cfg_attr(docsrs, doc(cfg(feature = "time-0_3")))] |
| 525 |
impl From<time::OffsetDateTime> for crate::DateTime { |
| 526 |
fn from(x: time::OffsetDateTime) -> Self { |
| 527 |
Self::from_time_0_3(x) |
| 528 |
} |
| 529 |
} |
| 530 |
|
| 531 |
#[cfg(all(feature = "time-0_3", feature = "serde_with"))] |
| 532 |
#[cfg_attr(docsrs, doc(cfg(all(feature = "time-0_3", feature = "serde_with"))))] |
| 533 |
impl<'de> DeserializeAs<'de, time::OffsetDateTime> for crate::DateTime { |
| 534 |
fn deserialize_as<D>(deserializer: D) -> std::result::Result<time::OffsetDateTime, D::Error> |
| 535 |
where |
| 536 |
D: Deserializer<'de>, |
| 537 |
{ |
| 538 |
let dt = DateTime::deserialize(deserializer)?; |
| 539 |
Ok(dt.to_time_0_3()) |
| 540 |
} |
| 541 |
} |
| 542 |
|
| 543 |
#[cfg(all(feature = "time-0_3", feature = "serde_with"))] |
| 544 |
#[cfg_attr(docsrs, doc(cfg(all(feature = "time-0_3", feature = "chrono-0_4"))))] |
| 545 |
impl SerializeAs<time::OffsetDateTime> for crate::DateTime { |
| 546 |
fn serialize_as<S>( |
| 547 |
source: &time::OffsetDateTime, |
| 548 |
serializer: S, |
| 549 |
) -> std::result::Result<S::Ok, S::Error> |
| 550 |
where |
| 551 |
S: serde::Serializer, |
| 552 |
{ |
| 553 |
let dt = DateTime::from_time_0_3(*source); |
| 554 |
dt.serialize(serializer) |
| 555 |
} |
| 556 |
} |
| 557 |
|
| 558 |
#[cfg(all(feature = "time-0_3", feature = "serde_with-3"))] |
| 559 |
#[cfg_attr(docsrs, doc(cfg(all(feature = "time-0_3", feature = "serde_with-3"))))] |
| 560 |
impl<'de> serde_with_3::DeserializeAs<'de, time::OffsetDateTime> for crate::DateTime { |
| 561 |
fn deserialize_as<D>(deserializer: D) -> std::result::Result<time::OffsetDateTime, D::Error> |
| 562 |
where |
| 563 |
D: Deserializer<'de>, |
| 564 |
{ |
| 565 |
let dt = DateTime::deserialize(deserializer)?; |
| 566 |
Ok(dt.to_time_0_3()) |
| 567 |
} |
| 568 |
} |
| 569 |
|
| 570 |
#[cfg(all(feature = "time-0_3", feature = "serde_with-3"))] |
| 571 |
#[cfg_attr(docsrs, doc(cfg(all(feature = "time-0_3", feature = "chrono-0_4"))))] |
| 572 |
impl serde_with_3::SerializeAs<time::OffsetDateTime> for crate::DateTime { |
| 573 |
fn serialize_as<S>( |
| 574 |
source: &time::OffsetDateTime, |
| 575 |
serializer: S, |
| 576 |
) -> std::result::Result<S::Ok, S::Error> |
| 577 |
where |
| 578 |
S: serde::Serializer, |
| 579 |
{ |
| 580 |
let dt = DateTime::from_time_0_3(*source); |
| 581 |
dt.serialize(serializer) |
| 582 |
} |
| 583 |
} |
| 584 |
|
| 585 |
/// Errors that can occur during [`DateTime`] construction and generation. |
| 586 |
#[derive(Clone, Debug)] |
| 587 |
#[non_exhaustive] |
| 588 |
pub enum Error { |
| 589 |
/// Error returned when an invalid datetime format is provided to a conversion method. |
| 590 |
#[non_exhaustive] |
| 591 |
InvalidTimestamp { message: String }, |
| 592 |
/// Error returned when a [`DateTime`] cannot be represented in a particular format. |
| 593 |
#[non_exhaustive] |
| 594 |
CannotFormat { message: String }, |
| 595 |
} |
| 596 |
|
| 597 |
/// Alias for `Result<T, DateTime::Error>` |
| 598 |
pub type Result<T> = result::Result<T, Error>; |
| 599 |
|
| 600 |
impl fmt::Display for Error { |
| 601 |
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |
| 602 |
match self { |
| 603 |
Error::InvalidTimestamp { message } | Error::CannotFormat { message } => { |
| 604 |
write!(fmt, "{}", message) |
| 605 |
} |
| 606 |
} |
| 607 |
} |
| 608 |
} |
| 609 |
|
| 610 |
impl error::Error for Error {} |