work_tock_lib/
s_time.rs

1use chrono::naive::NaiveDate;
2use chrono::offset::Local;
3use chrono::Timelike;
4use derive_more::*;
5use gobble::Parser;
6use std::fmt::{Debug, Display, Formatter};
7use std::str::FromStr;
8
9//use pest::Parser;
10
11use crate::err::TokErr;
12//use crate::pesto::{LineNum, Pestable, Rule, TimeFile};
13
14#[derive(Copy, Clone, PartialOrd, PartialEq, Eq, Add, Sub, AddAssign, SubAssign)]
15pub struct STime(isize); //minutes
16
17impl STime {
18    pub fn new(hr: isize, min: isize) -> Self {
19        STime(hr * 60 + min)
20    }
21    pub fn now() -> Self {
22        let t = Local::now();
23        STime::new(t.time().hour() as isize, t.time().minute() as isize)
24    }
25
26    pub fn since(&self, now_date: &NaiveDate, then_time: Self, then_date: &NaiveDate) -> Self {
27        let days_between = (*now_date - *then_date).num_days() as isize;
28        *self + STime::new(24 * days_between, 0) - then_time
29    }
30}
31
32impl FromStr for STime {
33    type Err = TokErr;
34    fn from_str(s: &str) -> Result<Self, TokErr> {
35        Ok(crate::gob::STIME.parse_s(s).map_err(|e| e.strung())?)
36    }
37}
38
39impl Debug for STime {
40    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
41        write!(f, "{:02}:{:02}", self.0 / 60, self.0 % 60)
42    }
43}
44
45impl Display for STime {
46    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
47        write!(f, "{:?}", self)
48    }
49}
50
51#[cfg(test)]
52mod test {
53    use super::*;
54    #[test]
55    pub fn test_stime_parse() {
56        assert!("243430343090349309309430334390:54"
57            .parse::<STime>()
58            .is_err());
59        assert_eq!("24:54".parse(), Ok(STime::new(24, 54)));
60    }
61}