use qx_rs_err::err::*;
use chrono::prelude::*;
pub enum Pattern {
Standard,
Date,
Time,
}
impl Pattern {
pub fn fmt<'a>(&self) -> &'a str {
match &self {
Pattern::Standard => {
return "%Y-%m-%d %H:%M:%S";
},
Pattern::Date => {
return "%Y-%m-%d";
},
Pattern::Time => {
return "%H:%M:%S";
}
}
}
}
pub fn now() -> DateTime<Utc> {
let dt = Utc::now();
return dt;
}
pub fn add_secs(time: DateTime<Utc>, secs: i64) -> DateTime<Utc> {
time + chrono::Duration::seconds(secs)
}
pub fn format(time: DateTime<Utc>, pattern: Pattern, time_zone: i32) -> String {
let tz_offset = FixedOffset::east_opt(time_zone * 3600).unwrap();
let tz_time = tz_offset.from_utc_datetime(&time.naive_utc());
return tz_time.format( pattern.fmt()).to_string();
}
pub fn parse(time_str: &str, pattern: Pattern, time_zone: i32) -> Result<DateTime<Utc>> {
let _dt_zone = format!(" +0{}00", time_zone);
let _time_str: String;
let _fmt: String;
match pattern {
Pattern::Standard => {
_time_str = format!("{}.000{}", time_str, _dt_zone);
_fmt = format!("{}%.3f %z", pattern.fmt());
},
Pattern::Date => {
_time_str = format!("{} 00:00:00.000{}", time_str, _dt_zone);
_fmt = format!("{} %H:%M:%S%.3f %z", pattern.fmt());
},
Pattern::Time => {
_time_str = format!("1971-01-01 {}.000{}", time_str, _dt_zone);
_fmt = format!("%Y-%m-%d {}%.3f %z", pattern.fmt());
}
}
let date_time = DateTime::parse_from_str(&_time_str, &_fmt).map_err(|err| {
Error::error(Box::new(err))
})?;
Ok(date_time.with_timezone(&Utc))
}
pub fn equal_year(a: DateTime<Utc>, b: DateTime<Utc>) -> bool {
a.year() == b.year()
}
pub fn equal_month(a: DateTime<Utc>, b: DateTime<Utc>) -> bool {
equal_year(a, b) && a.month() == b.month()
}
pub fn equal_day(a: DateTime<Utc>, b: DateTime<Utc>) -> bool {
equal_month(a, b) && a.date_naive() == b.date_naive()
}
pub fn equal_hour(a: DateTime<Utc>, b: DateTime<Utc>) -> bool {
equal_day(a, b) && a.hour() == b.hour()
}
pub fn equal_minute(a: DateTime<Utc>, b: DateTime<Utc>) -> bool {
equal_hour(a, b) && a.minute() == b.minute()
}
pub fn equal_second(a: DateTime<Utc>, b: DateTime<Utc>) -> bool {
equal_minute(a, b) && a.second() == b.second()
}