parse_rs/types/
date.rs

1// src/types/date.rs
2use chrono::{DateTime, Utc};
3use serde::{Deserialize, Serialize};
4use std::fmt;
5
6/// Represents a Parse Date type, which includes timezone information.
7/// Parse stores dates in UTC.
8#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
9pub struct ParseDate {
10    #[serde(rename = "__type")]
11    pub __type: String, // Should always be "Date"
12    pub iso: String, // ISO 8601 format, e.g., "YYYY-MM-DDTHH:MM:SS.MMMZ"
13}
14
15impl fmt::Display for ParseDate {
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17        write!(f, "{}", self.iso)
18    }
19}
20
21impl ParseDate {
22    /// Creates a new ParseDate from an ISO 8601 string.
23    /// Note: This does not validate the string format.
24    pub fn new(iso_string: impl Into<String>) -> Self {
25        ParseDate {
26            __type: "Date".to_string(),
27            iso: iso_string.into(),
28        }
29    }
30
31    /// Creates a new ParseDate representing the current time in UTC.
32    pub fn now() -> Self {
33        Self::from_datetime(Utc::now())
34    }
35
36    /// Creates a new ParseDate from a chrono::DateTime<Utc> object.
37    pub fn from_datetime(dt: DateTime<Utc>) -> Self {
38        ParseDate {
39            __type: "Date".to_string(),
40            iso: dt.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
41        }
42    }
43
44    /// Attempts to parse the ISO string into a chrono::DateTime<Utc> object.
45    pub fn to_datetime(&self) -> Result<DateTime<Utc>, chrono::ParseError> {
46        DateTime::parse_from_rfc3339(&self.iso).map(|dt| dt.with_timezone(&Utc))
47    }
48}