Parse times more like what people expect -- 07:30 is 7h30m, not 7m30s

This commit is contained in:
Dustin Carlino 2021-01-12 12:49:07 -08:00
parent f680de73aa
commit 549a625d57

View File

@ -102,22 +102,13 @@ impl Time {
bail!("Time {}: no :'s", string);
}
let mut seconds: f64 = 0.0;
if parts.last().unwrap().contains('.') {
let last_parts: Vec<&str> = parts.last().unwrap().split('.').collect();
if last_parts.len() != 2 {
bail!("Time {}: no . in last part", string);
}
seconds += last_parts[1].parse::<f64>()? / 10.0;
seconds += last_parts[0].parse::<f64>()?;
} else {
seconds += parts.last().unwrap().parse::<f64>()?;
}
let mut seconds = parts.last().unwrap().parse::<f64>()?;
match parts.len() {
1 => Ok(Time::seconds_since_midnight(seconds)),
2 => {
seconds += 60.0 * parts[0].parse::<f64>()?;
// They're really minutes
seconds *= 60.0;
seconds += 3600.0 * parts[0].parse::<f64>()?;
Ok(Time::seconds_since_midnight(seconds))
}
3 => {
@ -213,3 +204,27 @@ impl ops::Sub for Time {
Duration::seconds(self.0 - other.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse() {
assert_eq!(
Time::START_OF_DAY + Duration::seconds(42.3),
Time::parse("42.3").unwrap()
);
assert_eq!(
Time::START_OF_DAY + Duration::hours(7) + Duration::minutes(30),
Time::parse("07:30").unwrap()
);
assert_eq!(
Time::START_OF_DAY
+ Duration::hours(7)
+ Duration::minutes(30)
+ Duration::seconds(5.0),
Time::parse("07:30:05").unwrap()
);
}
}