use time::{format_description::FormatItem, macros::format_description};
use crate::{time::Format, Time};
pub const SHORT: &[FormatItem<'_>] = format_description!("[year]-[month]-[day]");
pub const RFC2822: &[FormatItem<'_>] = format_description!(
"[weekday repr:short], [day] [month repr:short] [year] [hour]:[minute]:[second] [offset_hour sign:mandatory][offset_minute]"
);
pub const GIT_RFC2822: &[FormatItem<'_>] = format_description!(
"[weekday repr:short], \
[day padding:none] \
[month repr:short] \
[year] \
[hour]:[minute]:[second] \
[offset_hour sign:mandatory][offset_minute]"
);
pub const ISO8601: &[FormatItem<'_>] =
format_description!("[year]-[month]-[day] [hour]:[minute]:[second] [offset_hour sign:mandatory][offset_minute]");
pub const ISO8601_STRICT: &[FormatItem<'_>] =
format_description!("[year]-[month]-[day]T[hour]:[minute]:[second][offset_hour sign:mandatory]:[offset_minute]");
pub const UNIX: Format<'static> = Format::Unix;
pub const RAW: Format<'static> = Format::Raw;
pub const GITOXIDE: &[FormatItem<'_>] = format_description!(
"[weekday repr:short] [month repr:short] [day] [year] [hour]:[minute]:[second] [offset_hour sign:mandatory][offset_minute]"
);
pub const DEFAULT: &[FormatItem<'_>] = format_description!(
"[weekday repr:short] \
[month repr:short] \
[day padding:none] \
[hour]:[minute]:[second] \
[year] \
[offset_hour sign:mandatory][offset_minute]"
);
mod format_impls {
use time::format_description::FormatItem;
use crate::time::Format;
impl<'a> From<&'a [FormatItem<'a>]> for Format<'a> {
fn from(f: &'a [FormatItem<'a>]) -> Self {
Format::Custom(f)
}
}
}
impl Time {
pub fn format<'a>(&self, format: impl Into<Format<'a>>) -> String {
self.format_inner(format.into())
}
fn format_inner(&self, format: Format<'_>) -> String {
match format {
Format::Custom(format) => self
.to_time()
.format(&format)
.expect("well-known format into memory never fails"),
Format::Unix => self.seconds.to_string(),
Format::Raw => self.to_bstring().to_string(),
}
}
}
impl Time {
fn to_time(self) -> time::OffsetDateTime {
time::OffsetDateTime::from_unix_timestamp(self.seconds)
.expect("always valid unix time")
.to_offset(time::UtcOffset::from_whole_seconds(self.offset).expect("valid offset"))
}
}