jt_util 0.1.1

jt808 jt1078等基础库实现
Documentation


use chrono::{ DateTime, Datelike, Local, TimeZone, Timelike};

pub struct TimeHelper {}

impl TimeHelper {
    pub fn time_diff_sec(rt: &DateTime<Local>) -> i64 {
        (Local::now() - *rt).num_seconds()
    }
    pub fn timeout(rt: &DateTime<Local>, outsec: i64) -> bool {
        Self::time_diff_sec(rt) > outsec
    }

    pub(crate) fn i32_to_bcd2(val: i32) -> u8 {
        let val = val.to_string();
        let (_f, v) = val.split_at(val.len() - 2);
        match u8::from_str_radix(v, 16) {
            Ok(v) => v,
            Err(_) => 0,
        }
    }
    pub(crate) fn u32_to_bcd2(val: u32) -> u8 {
        let val = val.to_string();
        match u8::from_str_radix(&val, 16) {
            Ok(v) => v,
            Err(_) => 0,
        }
    }
    pub fn datetime_add_secs(time:DateTime<Local>, secs:i64) -> DateTime<Local> {
        let unixtime = time.timestamp() + secs;
        Local.timestamp(unixtime, 0)
    }

    pub fn datetime_to_bcd6(rt: &DateTime<Local>) -> [u8;6] {

        let year = (rt.year() % 100) as u8;
        let month = rt.month() as u8;
        let day = rt.day() as u8;
        let hour = rt.hour() as u8;
        let minute = rt.minute() as u8;
        let second = rt.second() as u8;

        [year, month, day, hour, minute, second]
    }

    pub fn bcd6_to_datetme(data : [u8;6]) -> DateTime<Local> {
        
        let year = 2000 + data[0] as i32;

        Local
        .ymd(year, data[1].into(), data[2].into())
        .and_hms(data[3].into(), data[4].into(), data[5].into())
    }

}

#[test]
fn timer_helper_test() {
    let databytes_set:[u8;6] = [21, 11, 11, 9, 17, 18];
    let datatime_set = Local.ymd(2021, 11, 11).and_hms(9, 17, 18);
    let datatime_to = TimeHelper::bcd6_to_datetme(databytes_set);
    //println!("time: {}", datatime_set);
    //println!("time: {}", datatime_to);
    assert!(datatime_set.eq(&datatime_to));

    let data_bytes_to = TimeHelper::datetime_to_bcd6(&datatime_set);
    assert_eq!(data_bytes_to, databytes_set);

    //Local::now()
    
    //datatime convert timestamp
    //println!("timestamp: {}", datatime_set.timestamp() as u32);
    
    //timestamp convert datatime
    //println!("data: {}", Local.timestamp(1636593438, 0));

    //local.format("%Y-%m-%d %H:%M:%S%.3f").to_string()
}