use jiff::{civil, tz::TimeZone, Timestamp, Zoned};
pub fn parse(s: &str, tz: &TimeZone) -> Result<Zoned, DateError> {
let s = s.trim();
if s.is_empty() {
return Err(DateError(String::new()));
}
if let Some(ts) = parse_i64(s) {
return Timestamp::from_second(ts)
.map(|t| t.to_zoned(tz.clone()))
.map_err(|_| DateError(s.to_string()));
}
parse_format(s, tz).ok_or_else(|| DateError(s.to_string()))
}
fn parse_format(s: &str, tz: &TimeZone) -> Option<Zoned> {
let b = s.as_bytes();
if b.len() == 10 {
return s
.parse::<civil::Date>()
.ok()
.and_then(|d| d.to_zoned(tz.clone()).ok());
}
if b.len() > 10 {
match b[10] {
b'T' => {
if ends_with_offset(b) {
if let Ok(ts) = s.parse::<Timestamp>() {
return Some(ts.to_zoned(tz.clone()));
}
}
if let Ok(dt) = s.parse::<civil::DateTime>() {
return dt.to_zoned(tz.clone()).ok();
}
}
b' ' => {
let mut swapped = String::with_capacity(s.len());
swapped.push_str(&s[..10]);
swapped.push('T');
swapped.push_str(&s[11..]);
if let Ok(dt) = swapped.parse::<civil::DateTime>() {
return dt.to_zoned(tz.clone()).ok();
}
if ends_with_offset(swapped.as_bytes()) {
if let Ok(ts) = swapped.parse::<Timestamp>() {
return Some(ts.to_zoned(tz.clone()));
}
}
}
_ => {}
}
}
if let Ok(ts) = s.parse::<Timestamp>() {
return Some(ts.to_zoned(tz.clone()));
}
if let Ok(dt) = s.parse::<civil::DateTime>() {
return dt.to_zoned(tz.clone()).ok();
}
if let Ok(d) = s.parse::<civil::Date>() {
return d.to_zoned(tz.clone()).ok();
}
None
}
fn ends_with_offset(b: &[u8]) -> bool {
match b.last() {
Some(b'Z' | b'z') => true,
_ => b.len() >= 6 && matches!(b[b.len() - 6], b'+' | b'-') && b[b.len() - 3] == b':',
}
}
pub fn parse_i64(s: &str) -> Option<i64> {
let b = s.as_bytes();
if b.is_empty() {
return None;
}
let neg = b[0] == b'-';
let mut i = usize::from(neg || b[0] == b'+');
if i >= b.len() {
return None;
}
let mut n: i64 = 0;
while i < b.len() {
let c = b[i].wrapping_sub(b'0');
if c > 9 {
return None;
}
n = n.checked_mul(10)?.checked_add(c as i64)?;
i += 1;
}
Some(if neg { -n } else { n })
}
#[derive(Debug)]
pub struct DateError(String);
impl std::fmt::Display for DateError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "invalid date: {:?}", self.0)
}
}
impl std::error::Error for DateError {}