use chrono::{Datelike, Timelike};
use facet::Facet;
use xur_runtime::{OptionalArg, Registry, XurStr};
#[derive(Clone, Copy, Facet)]
#[repr(C)]
pub enum Error {
InvalidTimestamp,
Parse,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Error::InvalidTimestamp => "invalid timestamp",
Error::Parse => "failed to parse datetime",
})
}
}
pub(crate) fn register(registry: &Registry) {
registry.lazy_module("std::datetime", |module| {
module.ty::<Error>("Error");
module
.function("now", || DateTime(chrono::Local::now().fixed_offset()))
.function("utc_now", || DateTime(chrono::Utc::now().fixed_offset()))
.named_function("from_timestamp", &["secs"], |ts: i64| {
chrono::DateTime::from_timestamp(ts, 0)
.map(|dt| DateTime(dt.fixed_offset()))
.ok_or(Error::InvalidTimestamp)
})
.named_function(
"parse",
&["text", "format"],
|text: XurStr, format: OptionalArg<XurStr>| -> Result<DateTime, Error> {
let dt = match format.0 {
Some(fmt) => chrono::NaiveDateTime::parse_from_str(&text, &fmt)
.map_err(|_| Error::Parse)?
.and_utc()
.fixed_offset(),
None => chrono::DateTime::parse_from_rfc3339(&text)
.or_else(|_| chrono::DateTime::parse_from_rfc2822(&text))
.map_err(|_| Error::Parse)?,
};
Ok(DateTime(dt))
},
);
module
.ty::<DateTime>("DateTime")
.method("year", |d: &DateTime| d.0.year() as i64)
.method("month", |d: &DateTime| d.0.month() as i64)
.method("day", |d: &DateTime| d.0.day() as i64)
.method("hour", |d: &DateTime| d.0.hour() as i64)
.method("minute", |d: &DateTime| d.0.minute() as i64)
.method("second", |d: &DateTime| d.0.second() as i64)
.method("timestamp", |d: &DateTime| d.0.timestamp())
.method("timestamp_millis", |d: &DateTime| d.0.timestamp_millis())
.method("weekday", |d: &DateTime| d.0.format("%A").to_string())
.method("iso", |d: &DateTime| d.0.to_rfc3339())
.named_method("format", &["fmt"], |d: &DateTime, fmt: XurStr| {
d.0.format(&fmt).to_string()
})
.named_method("add_days", &["n"], |d: &DateTime, n: i64| {
DateTime(d.0 + chrono::TimeDelta::days(n))
})
.named_method("add_hours", &["n"], |d: &DateTime, n: i64| {
DateTime(d.0 + chrono::TimeDelta::hours(n))
})
.named_method("add_minutes", &["n"], |d: &DateTime, n: i64| {
DateTime(d.0 + chrono::TimeDelta::minutes(n))
})
.named_method("add_seconds", &["n"], |d: &DateTime, n: i64| {
DateTime(d.0 + chrono::TimeDelta::seconds(n))
})
.named_method("add_weeks", &["n"], |d: &DateTime, n: i64| {
DateTime(d.0 + chrono::TimeDelta::weeks(n))
})
.named_method("add_months", &["n"], |d: &DateTime, n: i64| {
add_months(d, n)
})
.named_method("add_years", &["n"], |d: &DateTime, n: i64| {
add_months(d, n * 12)
});
});
}
#[derive(Clone, Facet)]
#[facet(opaque)]
struct DateTime(chrono::DateTime<chrono::FixedOffset>);
impl std::fmt::Display for DateTime {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0.to_rfc3339())
}
}
fn add_months(d: &DateTime, months: i64) -> DateTime {
if months >= 0 {
DateTime(d.0 + chrono::Months::new(months as u32))
} else {
DateTime(d.0 - chrono::Months::new((-months) as u32))
}
}