use std::{fmt::Display, str::FromStr}; use anyhow::{Context, Result}; use chrono::{DateTime, Datelike as ChronoDatelike, NaiveDate, Timelike as ChronoTimelike, Utc}; use diesel::{ backend::Backend, deserialize::{self, FromSql, FromSqlRow}, expression::AsExpression, serialize::{self, ToSql}, sql_types::Text, sqlite::Sqlite, }; use serde::{Deserialize, Serialize}; use schist_traits::{Dateable, Nowlike, Timeable}; #[derive( PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Clone, Debug, AsExpression, FromSqlRow, )] #[diesel(sql_type=Text)] pub struct DatetimeUtc { chrono_datetime_utc: DateTime, } impl DatetimeUtc { pub fn from_ymd_and_hms( year: i32, month: u32, day: u32, hour: u32, min: u32, sec: u32, ) -> Result { Ok(Self { chrono_datetime_utc: NaiveDate::from_ymd_opt(year, month, day) .with_context(|| { format!( "failed to construct datetime from ymd {:04}-{:02}-{:02}", year, month, day ) })? .and_hms_opt(hour, min, sec) .with_context(|| { format!( "failed to construct datetime from hms {:02}:{:02}:{:02}", hour, min, sec ) })? .and_utc(), }) } } impl FromStr for DatetimeUtc { type Err = anyhow::Error; /// Constructs DatetimeUtc from a date string in ISO format, in UTC /// Example: "2024-10-24T10:30:00.000" -> 10.30am 24 Oct 2024 UTC fn from_str(datetime_str: &str) -> Result { let chrono_datetime_utc = datetime_str.parse::>()?; Ok(Self { chrono_datetime_utc, }) } } impl Display for DatetimeUtc { /// Converts to a date string in ISO format, in UTC /// Example: 10.30am 24 Oct 2024 UTC -> "2024-10-24T10:30:00.000Z" fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, "{}", self.chrono_datetime_utc .to_rfc3339_opts(chrono::SecondsFormat::Millis, true) ) } } impl Nowlike for DatetimeUtc { fn now() -> Self { let now = Utc::now(); Self::from_ymd_and_hms( now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second(), ) .unwrap() } } impl Dateable for DatetimeUtc { fn year(&self) -> i32 { self.chrono_datetime_utc.year() } fn month(&self) -> u32 { self.chrono_datetime_utc.month() } fn day(&self) -> u32 { self.chrono_datetime_utc.day() } } impl Timeable for DatetimeUtc { fn hour(&self) -> u32 { self.chrono_datetime_utc.hour() } fn minute(&self) -> u32 { self.chrono_datetime_utc.minute() } fn second(&self) -> u32 { self.chrono_datetime_utc.second() } } impl ToSql for DatetimeUtc { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, Sqlite>, ) -> serialize::Result { out.set_value::(self.to_string()); Ok(serialize::IsNull::No) } } impl FromSql for DatetimeUtc { fn from_sql(bytes: ::RawValue<'_>) -> deserialize::Result { let str = >::from_sql(bytes)?; Ok(str.parse()?) } } #[cfg(test)] mod test { use super::*; #[test] fn when_from_ymd_and_hms_then_ymd_and_hms_are_as_expected() { let datetime_utc = DatetimeUtc::from_ymd_and_hms(1970, 11, 23, 12, 55, 16); assert!(datetime_utc.is_ok()); let date_utc = datetime_utc.unwrap(); assert_eq!(date_utc.year(), 1970); assert_eq!(date_utc.month(), 11); assert_eq!(date_utc.day(), 23); assert_eq!(date_utc.hour(), 12); assert_eq!(date_utc.minute(), 55); assert_eq!(date_utc.second(), 16); } #[test] fn when_from_ymd_and_hms_then_to_string_as_expected() { let date_utc = DatetimeUtc::from_ymd_and_hms(1970, 11, 23, 12, 55, 16); assert!(date_utc.is_ok()); assert_eq!(date_utc.unwrap().to_string(), "1970-11-23T12:55:16.000Z") } #[test] fn when_with_invalid_ymd_and_hms_then_err() { let datetime_utc_1 = DatetimeUtc::from_ymd_and_hms(1970, 0, 23, 12, 55, 16); let datetime_utc_2 = DatetimeUtc::from_ymd_and_hms(1970, 13, 23, 12, 55, 16); let datetime_utc_3 = DatetimeUtc::from_ymd_and_hms(1970, 11, 0, 12, 55, 16); let datetime_utc_4 = DatetimeUtc::from_ymd_and_hms(1970, 11, 31, 12, 55, 16); let datetime_utc_5 = DatetimeUtc::from_ymd_and_hms(1971, 2, 29, 12, 55, 16); let datetime_utc_6 = DatetimeUtc::from_ymd_and_hms(1970, 11, 23, 25, 0, 0); let datetime_utc_7 = DatetimeUtc::from_ymd_and_hms(1970, 11, 23, 0, 61, 0); let datetime_utc_8 = DatetimeUtc::from_ymd_and_hms(1970, 11, 23, 0, 0, 61); assert!(datetime_utc_1.is_err()); assert_eq!( datetime_utc_1.unwrap_err().to_string(), "failed to construct datetime from ymd 1970-00-23" ); assert!(datetime_utc_2.is_err()); assert_eq!( datetime_utc_2.unwrap_err().to_string(), "failed to construct datetime from ymd 1970-13-23" ); assert!(datetime_utc_3.is_err()); assert_eq!( datetime_utc_3.unwrap_err().to_string(), "failed to construct datetime from ymd 1970-11-00" ); assert!(datetime_utc_4.is_err()); assert_eq!( datetime_utc_4.unwrap_err().to_string(), "failed to construct datetime from ymd 1970-11-31" ); assert!(datetime_utc_5.is_err()); assert_eq!( datetime_utc_5.unwrap_err().to_string(), "failed to construct datetime from ymd 1971-02-29" ); assert!(datetime_utc_6.is_err()); assert_eq!( datetime_utc_6.unwrap_err().to_string(), "failed to construct datetime from hms 25:00:00" ); assert!(datetime_utc_7.is_err()); assert_eq!( datetime_utc_7.unwrap_err().to_string(), "failed to construct datetime from hms 00:61:00" ); assert!(datetime_utc_8.is_err()); assert_eq!( datetime_utc_8.unwrap_err().to_string(), "failed to construct datetime from hms 00:00:61" ); } #[test] fn when_from_string_then_ymd_and_hms_are_as_expected() { let date_utc: Result = "1970-11-23T12:55:16.000Z".parse(); assert!(date_utc.is_ok()); let datetime_utc = date_utc.unwrap(); assert_eq!(datetime_utc.year(), 1970); assert_eq!(datetime_utc.month(), 11); assert_eq!(datetime_utc.day(), 23); assert_eq!(datetime_utc.hour(), 12); assert_eq!(datetime_utc.minute(), 55); assert_eq!(datetime_utc.second(), 16); } #[test] fn when_from_string_then_to_string_as_expected() { let datetime_utc: Result = "1970-11-23T12:55:16.000Z".parse(); assert!(datetime_utc.is_ok()); assert_eq!( datetime_utc.unwrap().to_string(), "1970-11-23T12:55:16.000Z" ) } #[test] fn when_from_invalid_string_then_err() { let datetime_utc_1: Result = "1970-00-23T00:00:00.000Z".parse(); let datetime_utc_2: Result = "1970-13-23T00:00:00.000Z".parse(); let datetime_utc_3: Result = "1970-11-0T00:00:00.000Z".parse(); let datetime_utc_4: Result = "1970-11-31T00:00:00.000Z".parse(); let datetime_utc_5: Result = "1971-02-29T00:00:00.000Z".parse(); let datetime_utc_6: Result = "1970-11-23T25:00:00.000Z".parse(); let datetime_utc_7: Result = "1970-11-23T00:61:00.000Z".parse(); let datetime_utc_8: Result = "1970-11-23T00:00:61.000Z".parse(); assert!(datetime_utc_1.is_err()); assert!(datetime_utc_2.is_err()); assert!(datetime_utc_3.is_err()); assert!(datetime_utc_4.is_err()); assert!(datetime_utc_5.is_err()); assert!(datetime_utc_6.is_err()); assert!(datetime_utc_7.is_err()); assert!(datetime_utc_8.is_err()); } }