moved datetime functions to utils dir
This commit is contained in:
56
backend/public/src/utils/datetime.rs
Normal file
56
backend/public/src/utils/datetime.rs
Normal file
@ -0,0 +1,56 @@
|
||||
use chrono::Utc;
|
||||
use serde::{Deserializer, Serializer};
|
||||
use std::fmt;
|
||||
|
||||
pub fn serialize_datetime<S>(
|
||||
date: &Option<chrono::DateTime<Utc>>,
|
||||
serializer: S,
|
||||
) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(&date.unwrap().to_rfc3339())
|
||||
}
|
||||
|
||||
pub fn deserialize_datetime<'de, D>(
|
||||
deserializer: D,
|
||||
) -> Result<Option<chrono::DateTime<Utc>>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
struct DateTimeVisitor;
|
||||
|
||||
impl<'de> serde::de::Visitor<'de> for DateTimeVisitor {
|
||||
type Value = Option<chrono::DateTime<Utc>>;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
formatter.write_str("an ISO 8601 formatted date string or null")
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
|
||||
where
|
||||
E: serde::de::Error,
|
||||
{
|
||||
match chrono::DateTime::parse_from_rfc3339(value) {
|
||||
Ok(dt) => Ok(Some(dt.with_timezone(&Utc))),
|
||||
Err(e) => Err(E::custom(format!("Failed to parse datetime: {}", e))),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_none<E>(self) -> Result<Self::Value, E>
|
||||
where
|
||||
E: serde::de::Error,
|
||||
{
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
deserializer.deserialize_str(self)
|
||||
}
|
||||
}
|
||||
|
||||
deserializer.deserialize_option(DateTimeVisitor)
|
||||
}
|
@ -1 +1,2 @@
|
||||
pub mod datetime;
|
||||
pub mod rss;
|
||||
|
Reference in New Issue
Block a user