use chrono::{NaiveDate, Utc};
use std::{error::Error, fmt};
#[derive(Debug)]
struct FormatError;
impl Error for FormatError {}
impl fmt::Display for FormatError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Input not formatted correctly")
}
}
pub fn parse_date(date: Option<String>) -> Result<String, Box<dyn Error>> {
if let Some(date) = date {
let date_parsed = NaiveDate::parse_from_str(&date, "%d/%m/%Y")?;
return Ok(date_parsed.format("%d/%m/%Y").to_string());
} else {
return Ok(Utc::now().format("%d/%m/%Y").to_string());
}
}
pub fn parse_premium(premium: f32) -> Result<f32, Box<dyn Error>> {
if premium == 0. {
return Ok(0.);
} else {
return Ok(premium / 100.);
}
}
pub fn parse_time(time: Option<String>, default: f32) -> Result<f32, Box<dyn Error>> {
if let Some(time) = time {
if time.split(':').count() == 2 {
let split = time.split(':').collect::<Vec<&str>>();
Ok(split[0].parse::<f32>()? + (split[1].parse::<f32>()? / 60.))
} else {
Err(Box::new(FormatError))
}
} else {
Ok(default)
}
}
pub fn parse_month(date: Option<String>) -> Result<String, Box<dyn Error>> {
if let Some(date) = date {
NaiveDate::parse_from_str(&format!("01/{}", &date), "%d/%m/%Y")?;
return Ok(date);
} else {
return Ok(Utc::now().format("%m/%Y").to_string());
}
}