use super::Object;
#[cfg(feature = "chrono")]
mod chrono_impl {
use crate::Object;
use crate::datetime::{date_literal, date_with_offset};
use chrono::prelude::*;
impl From<DateTime<FixedOffset>> for Object {
fn from(date: DateTime<FixedOffset>) -> Self {
date_with_offset(date.format("D:%Y%m%d%H%M%S%:z'").to_string())
}
}
impl From<DateTime<Utc>> for Object {
fn from(date: DateTime<Utc>) -> Self {
date_literal(date.format("D:%Y%m%d%H%M%SZ").to_string())
}
}
impl TryFrom<super::DateTime> for DateTime<FixedOffset> {
type Error = chrono::format::ParseError;
fn try_from(value: super::DateTime) -> Result<DateTime<FixedOffset>, Self::Error> {
let from_date = |date: NaiveDate| {
FixedOffset::east_opt(0)
.unwrap()
.from_utc_datetime(&date.and_time(NaiveTime::from_hms_opt(0, 0, 0).unwrap()))
};
let from_utc = |date: NaiveDateTime| FixedOffset::east_opt(0).unwrap().from_utc_datetime(&date);
DateTime::parse_from_str(&value.0, "%Y%m%d%H%M%S%#z")
.or_else(|_| DateTime::parse_from_str(&value.0, "%Y%m%d%H%M%#z"))
.or_else(|_| NaiveDateTime::parse_from_str(&value.0, "%Y%m%d%H%M%S").map(from_utc))
.or_else(|_| NaiveDateTime::parse_from_str(&value.0, "%Y%m%d%H%M").map(from_utc))
.or_else(|_| NaiveDate::parse_from_str(&value.0, "%Y%m%d").map(from_date))
}
}
}
#[cfg(feature = "chrono-clock")]
mod chrono_clock_impl {
use crate::Object;
use crate::datetime::date_with_offset;
use chrono::prelude::*;
impl From<DateTime<Local>> for Object {
fn from(date: DateTime<Local>) -> Self {
date_with_offset(date.format("D:%Y%m%d%H%M%S%:z'").to_string())
}
}
impl TryFrom<super::DateTime> for DateTime<Local> {
type Error = chrono::format::ParseError;
fn try_from(value: super::DateTime) -> Result<DateTime<Local>, Self::Error> {
DateTime::<FixedOffset>::try_from(value).map(|date| date.with_timezone(&Local))
}
}
}
#[cfg(feature = "jiff")]
mod jiff_impl {
use crate::Object;
use crate::datetime::{date_literal, date_with_offset};
use jiff::{Timestamp, Zoned};
impl From<Zoned> for Object {
fn from(date: Zoned) -> Self {
date_with_offset(date.strftime("D:%Y%m%d%H%M%S%:z'").to_string())
}
}
impl From<Timestamp> for Object {
fn from(date: Timestamp) -> Self {
date_literal(date.strftime("D:%Y%m%d%H%M%SZ").to_string())
}
}
impl TryFrom<super::DateTime> for Zoned {
type Error = jiff::Error;
fn try_from(value: super::DateTime) -> Result<Self, Self::Error> {
use jiff::civil::{Date, DateTime};
Zoned::strptime("%Y%m%d%H%M%S%#z", &value.0)
.or_else(|_| DateTime::strptime("%Y%m%d%H%M%SZ", &value.0).and_then(|dt| dt.in_tz("UTC")))
.or_else(|_| Zoned::strptime("%Y%m%d%H%M%#z", &value.0))
.or_else(|_| DateTime::strptime("%Y%m%d%H%MZ", &value.0).and_then(|dt| dt.in_tz("UTC")))
.or_else(|_| DateTime::strptime("%Y%m%d%H%M%S", &value.0).and_then(|dt| dt.in_tz("GMT")))
.or_else(|_| DateTime::strptime("%Y%m%d%H%M", &value.0).and_then(|dt| dt.in_tz("GMT")))
.or_else(|_| Date::strptime("%Y%m%d", &value.0).and_then(|dt| dt.at(0, 0, 0, 0).in_tz("GMT")))
}
}
}
#[cfg(feature = "time")]
mod time_impl {
use super::date_literal;
use crate::Object;
use time::{OffsetDateTime, PrimitiveDateTime};
impl From<PrimitiveDateTime> for Object {
fn from(date: PrimitiveDateTime) -> Self {
let format =
time::format_description::parse_borrowed::<3>("D:[year][month][day][hour][minute][second]Z").unwrap();
date_literal(date.format(&format).unwrap())
}
}
impl From<OffsetDateTime> for Object {
fn from(date: OffsetDateTime) -> Self {
let format = time::format_description::parse_borrowed::<3>(
"D:[year][month][day][hour][minute][second][offset_hour sign:mandatory]'[offset_minute]'",
)
.unwrap();
date_literal(date.format(&format).unwrap())
}
}
impl TryFrom<super::DateTime> for OffsetDateTime {
type Error = time::Error;
fn try_from(value: super::DateTime) -> Result<OffsetDateTime, Self::Error> {
use time::format_description::parse_borrowed;
use time::{Date, PrimitiveDateTime};
let text = match value.0.strip_suffix('Z') {
Some(text) => format!("{text}+0000"),
None => value.0,
};
let parse = |format: &str| -> Result<OffsetDateTime, Self::Error> {
Ok(OffsetDateTime::parse(&text, &parse_borrowed::<3>(format)?)?)
};
let parse_utc = |format: &str| -> Result<OffsetDateTime, Self::Error> {
Ok(PrimitiveDateTime::parse(&text, &parse_borrowed::<3>(format)?)?.assume_utc())
};
parse("[year][month][day][hour][minute][second][offset_hour sign:mandatory][offset_minute]")
.or_else(|_| parse("[year][month][day][hour][minute][offset_hour sign:mandatory][offset_minute]"))
.or_else(|_| parse_utc("[year][month][day][hour][minute][second]"))
.or_else(|_| parse_utc("[year][month][day][hour][minute]"))
.or_else(|_| {
let date = Date::parse(&text, &parse_borrowed::<3>("[year][month][day]")?)?;
Ok(date.midnight().assume_utc())
})
}
}
}
#[cfg(any(feature = "chrono", feature = "jiff"))]
fn date_with_offset(text: String) -> Object {
let mut bytes = text.into_bytes();
convert_utc_offset(&mut bytes);
Object::string_literal(bytes)
}
#[cfg(any(feature = "chrono", feature = "jiff", feature = "time"))]
fn date_literal(text: String) -> Object {
Object::string_literal(text)
}
#[allow(dead_code)]
fn convert_utc_offset(bytes: &mut [u8]) {
let mut index = bytes.len();
while let Some(last) = bytes[..index].last_mut() {
if *last == b':' {
*last = b'\'';
break;
}
index -= 1;
}
}
#[derive(Clone, Debug)]
pub struct DateTime(String);
impl Object {
fn datetime_string(&self) -> Option<String> {
if let Object::String(bytes, _) = self {
String::from_utf8(bytes.iter().filter(|b| !b"D:'".contains(b)).cloned().collect()).ok()
} else {
None
}
}
pub fn as_datetime(&self) -> Option<DateTime> {
self.datetime_string().map(DateTime)
}
}
impl DateTime {
pub fn as_str(&self) -> &str {
&self.0
}
}
#[test]
fn a_datetime_is_readable_without_a_backend() {
let text = Object::string_literal("D:20260710143000+02'00'");
assert_eq!(text.as_datetime().unwrap().as_str(), "20260710143000+0200");
assert!(Object::Integer(20260710).as_datetime().is_none());
}
#[cfg(feature = "chrono")]
#[test]
fn parse_datetime_fixed_offset_keeps_the_offset_the_file_stated() {
use chrono::prelude::*;
let text = Object::string_literal("D:20260710143000+02'00'");
let date: DateTime<FixedOffset> = text.as_datetime().unwrap().try_into().unwrap();
assert_eq!(date.offset().local_minus_utc(), 2 * 3600);
assert_eq!(date.hour(), 14);
let back: Object = date.into();
assert_eq!(back, Object::string_literal("D:20260710143000+02'00'"));
}
#[cfg(feature = "chrono")]
#[test]
fn parse_datetime_fixed_offset_round_trip() {
use chrono::prelude::*;
let time = FixedOffset::east_opt(-5 * 3600 - 30 * 60)
.unwrap()
.with_ymd_and_hms(2026, 7, 10, 14, 30, 0)
.unwrap();
let text: Object = time.into();
let time2: Option<DateTime<FixedOffset>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
assert_eq!(time2, Some(time));
}
#[cfg(feature = "chrono-clock")]
#[test]
fn parse_datetime_local() {
use chrono::prelude::*;
let time = Local::now().with_nanosecond(0).unwrap();
let text: Object = time.into();
let time2: Option<DateTime<Local>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
assert_eq!(time2, Some(time));
}
#[cfg(feature = "chrono")]
#[test]
fn parse_datetime_utc() {
use chrono::prelude::*;
let time = Utc.with_ymd_and_hms(2026, 7, 10, 14, 30, 0).unwrap();
let text: Object = time.into();
let time2: Option<DateTime<FixedOffset>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
assert_eq!(time2, Some(time.fixed_offset()));
}
#[cfg(feature = "jiff")]
#[test]
fn parse_zoned() {
use jiff::Zoned;
let time = Zoned::now().with().subsec_nanosecond(0).build().unwrap();
let text: Object = time.clone().into();
let time2: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
assert_eq!(time2, Some(time));
}
#[cfg(feature = "jiff")]
#[test]
fn parse_timestamp() {
use jiff::Zoned;
let time = Zoned::now().with().subsec_nanosecond(0).build().unwrap();
let text: Object = time.timestamp().into();
let time2: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
assert_eq!(time2, Some(time));
}
#[cfg(feature = "chrono")]
#[test]
fn parse_datetime_seconds_missing_chrono() {
use chrono::prelude::*;
let text = Object::string_literal("D:199812231952-08'00'");
let dt: Option<DateTime<FixedOffset>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
assert!(dt.is_some());
}
#[cfg(feature = "chrono")]
#[test]
fn parse_datetime_time_missing_chrono() {
use chrono::prelude::*;
let text = Object::string_literal("D:20040229");
let dt: Option<DateTime<FixedOffset>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
assert!(dt.is_some());
}
#[cfg(feature = "jiff")]
#[test]
fn parse_datetime_seconds_missing_jiff() {
use jiff::Zoned;
let text = Object::string_literal("D:199812231952-08'00'");
let dt: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
assert!(dt.is_some());
}
#[cfg(feature = "jiff")]
#[test]
fn parse_datetime_time_missing_jiff() {
use jiff::Zoned;
let text = Object::string_literal("D:20040229");
let dt: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
assert!(dt.is_some());
}
#[cfg(feature = "time")]
#[test]
fn format_primitive_datetime_as_utc() {
use time::{Date, Month, PrimitiveDateTime, Time};
let date = Date::from_calendar_date(1998, Month::December, 23).unwrap();
let time = Time::from_hms(19, 52, 0).unwrap();
let text: Object = PrimitiveDateTime::new(date, time).into();
match &text {
Object::String(bytes, _) => assert_eq!(bytes.as_slice(), b"D:19981223195200Z"),
other => panic!("expected a string literal, got {other:?}"),
}
}
#[cfg(feature = "time")]
#[test]
fn parse_datetime() {
use time::OffsetDateTime;
let time = OffsetDateTime::now_utc();
let text: Object = time.into();
let time2: OffsetDateTime = text.as_datetime().unwrap().try_into().unwrap();
assert_eq!(time2.date(), time.date());
assert_eq!(time2.time().hour(), time.time().hour());
assert_eq!(time2.time().minute(), time.time().minute());
assert_eq!(time2.time().second(), time.time().second());
}
#[cfg(feature = "time")]
#[test]
fn parse_datetime_utc_time() {
use time::{Date, Month, OffsetDateTime, PrimitiveDateTime, Time};
let date = Date::from_calendar_date(1998, Month::December, 23).unwrap();
let time = PrimitiveDateTime::new(date, Time::from_hms(19, 52, 0).unwrap());
let text: Object = time.into();
let time2: Option<OffsetDateTime> = text.as_datetime().and_then(|dt| dt.try_into().ok());
assert_eq!(time2, Some(time.assume_utc()));
}
#[cfg(feature = "time")]
#[test]
fn parse_datetime_seconds_missing_time() {
use time::{OffsetDateTime, UtcOffset};
let text = Object::string_literal("D:199812231952-08'00'");
let dt: OffsetDateTime = text.as_datetime().unwrap().try_into().unwrap();
assert_eq!((dt.hour(), dt.minute(), dt.second()), (19, 52, 0));
assert_eq!(dt.offset(), UtcOffset::from_hms(-8, 0, 0).unwrap());
}
#[cfg(feature = "time")]
#[test]
fn parse_datetime_time_missing_time() {
use time::{Date, Month, OffsetDateTime};
let text = Object::string_literal("D:20040229");
let dt: OffsetDateTime = text.as_datetime().unwrap().try_into().unwrap();
let date = Date::from_calendar_date(2004, Month::February, 29).unwrap();
assert_eq!(dt, date.midnight().assume_utc());
}
#[cfg(feature = "chrono")]
#[test]
fn parse_datetime_offset_missing_chrono() {
use chrono::prelude::*;
let expected = Utc.with_ymd_and_hms(2024, 1, 15, 12, 30, 45).unwrap().fixed_offset();
let text = Object::string_literal("D:20240115123045");
let dt: Option<DateTime<FixedOffset>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
assert_eq!(dt, Some(expected));
let expected = Utc.with_ymd_and_hms(2024, 1, 15, 12, 30, 0).unwrap().fixed_offset();
let text = Object::string_literal("D:202401151230");
let dt: Option<DateTime<FixedOffset>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
assert_eq!(dt, Some(expected));
}
#[cfg(feature = "jiff")]
#[test]
fn parse_datetime_offset_missing_jiff() {
use jiff::{Timestamp, Zoned};
let text = Object::string_literal("D:20240115123045");
let dt: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
let expected: Timestamp = "2024-01-15T12:30:45Z".parse().unwrap();
assert_eq!(dt.map(|dt| dt.timestamp()), Some(expected));
let text = Object::string_literal("D:202401151230");
let dt: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
let expected: Timestamp = "2024-01-15T12:30:00Z".parse().unwrap();
assert_eq!(dt.map(|dt| dt.timestamp()), Some(expected));
}
#[cfg(feature = "time")]
#[test]
fn parse_datetime_offset_missing_time() {
use time::{Date, Month, OffsetDateTime, Time};
let date = Date::from_calendar_date(2024, Month::January, 15).unwrap();
let text = Object::string_literal("D:20240115123045");
let dt: Option<OffsetDateTime> = text.as_datetime().and_then(|dt| dt.try_into().ok());
let expected = date.with_time(Time::from_hms(12, 30, 45).unwrap()).assume_utc();
assert_eq!(dt, Some(expected));
let text = Object::string_literal("D:202401151230");
let dt: Option<OffsetDateTime> = text.as_datetime().and_then(|dt| dt.try_into().ok());
let expected = date.with_time(Time::from_hms(12, 30, 0).unwrap()).assume_utc();
assert_eq!(dt, Some(expected));
}